babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434
  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.addVector3 = function (otherVector) {
  412. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  413. };
  414. Vector2.prototype.subtract = function (otherVector) {
  415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  416. };
  417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  418. result.x = this.x - otherVector.x;
  419. result.y = this.y - otherVector.y;
  420. return this;
  421. };
  422. Vector2.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.multiplyInPlace = function (otherVector) {
  428. this.x *= otherVector.x;
  429. this.y *= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiply = function (otherVector) {
  433. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  434. };
  435. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  436. result.x = this.x * otherVector.x;
  437. result.y = this.y * otherVector.y;
  438. return this;
  439. };
  440. Vector2.prototype.multiplyByFloats = function (x, y) {
  441. return new Vector2(this.x * x, this.y * y);
  442. };
  443. Vector2.prototype.divide = function (otherVector) {
  444. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  445. };
  446. Vector2.prototype.divideToRef = function (otherVector, result) {
  447. result.x = this.x / otherVector.x;
  448. result.y = this.y / otherVector.y;
  449. return this;
  450. };
  451. Vector2.prototype.negate = function () {
  452. return new Vector2(-this.x, -this.y);
  453. };
  454. Vector2.prototype.scaleInPlace = function (scale) {
  455. this.x *= scale;
  456. this.y *= scale;
  457. return this;
  458. };
  459. Vector2.prototype.scale = function (scale) {
  460. return new Vector2(this.x * scale, this.y * scale);
  461. };
  462. Vector2.prototype.equals = function (otherVector) {
  463. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  464. };
  465. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  466. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  467. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  468. };
  469. // Properties
  470. Vector2.prototype.length = function () {
  471. return Math.sqrt(this.x * this.x + this.y * this.y);
  472. };
  473. Vector2.prototype.lengthSquared = function () {
  474. return (this.x * this.x + this.y * this.y);
  475. };
  476. // Methods
  477. Vector2.prototype.normalize = function () {
  478. var len = this.length();
  479. if (len === 0)
  480. return this;
  481. var num = 1.0 / len;
  482. this.x *= num;
  483. this.y *= num;
  484. return this;
  485. };
  486. Vector2.prototype.clone = function () {
  487. return new Vector2(this.x, this.y);
  488. };
  489. // Statics
  490. Vector2.Zero = function () {
  491. return new Vector2(0, 0);
  492. };
  493. Vector2.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Vector2(array[offset], array[offset + 1]);
  496. };
  497. Vector2.FromArrayToRef = function (array, offset, result) {
  498. result.x = array[offset];
  499. result.y = array[offset + 1];
  500. };
  501. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  502. var squared = amount * amount;
  503. var cubed = amount * squared;
  504. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  505. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  506. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  507. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  508. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  509. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  510. return new Vector2(x, y);
  511. };
  512. Vector2.Clamp = function (value, min, max) {
  513. var x = value.x;
  514. x = (x > max.x) ? max.x : x;
  515. x = (x < min.x) ? min.x : x;
  516. var y = value.y;
  517. y = (y > max.y) ? max.y : y;
  518. y = (y < min.y) ? min.y : y;
  519. return new Vector2(x, y);
  520. };
  521. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  522. var squared = amount * amount;
  523. var cubed = amount * squared;
  524. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  525. var part2 = (-2.0 * cubed) + (3.0 * squared);
  526. var part3 = (cubed - (2.0 * squared)) + amount;
  527. var part4 = cubed - squared;
  528. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  529. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  530. return new Vector2(x, y);
  531. };
  532. Vector2.Lerp = function (start, end, amount) {
  533. var x = start.x + ((end.x - start.x) * amount);
  534. var y = start.y + ((end.y - start.y) * amount);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Dot = function (left, right) {
  538. return left.x * right.x + left.y * right.y;
  539. };
  540. Vector2.Normalize = function (vector) {
  541. var newVector = vector.clone();
  542. newVector.normalize();
  543. return newVector;
  544. };
  545. Vector2.Minimize = function (left, right) {
  546. var x = (left.x < right.x) ? left.x : right.x;
  547. var y = (left.y < right.y) ? left.y : right.y;
  548. return new Vector2(x, y);
  549. };
  550. Vector2.Maximize = 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.Transform = function (vector, transformation) {
  556. var r = Vector2.Zero();
  557. Vector2.TransformToRef(vector, transformation, r);
  558. return r;
  559. };
  560. Vector2.TransformToRef = function (vector, transformation, result) {
  561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  563. result.x = x;
  564. result.y = y;
  565. };
  566. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  567. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  568. var sign = a < 0 ? -1 : 1;
  569. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  570. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  571. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  572. };
  573. Vector2.Distance = function (value1, value2) {
  574. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  575. };
  576. Vector2.DistanceSquared = function (value1, value2) {
  577. var x = value1.x - value2.x;
  578. var y = value1.y - value2.y;
  579. return (x * x) + (y * y);
  580. };
  581. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  582. var l2 = Vector2.DistanceSquared(segA, segB);
  583. if (l2 === 0.0) {
  584. return Vector2.Distance(p, segA);
  585. }
  586. var v = segB.subtract(segA);
  587. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  588. var proj = segA.add(v.multiplyByFloats(t, t));
  589. return Vector2.Distance(p, proj);
  590. };
  591. return Vector2;
  592. })();
  593. BABYLON.Vector2 = Vector2;
  594. var Vector3 = (function () {
  595. function Vector3(x, y, z) {
  596. this.x = x;
  597. this.y = y;
  598. this.z = z;
  599. }
  600. Vector3.prototype.toString = function () {
  601. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  602. };
  603. Vector3.prototype.getClassName = function () {
  604. return "Vector3";
  605. };
  606. Vector3.prototype.getHashCode = function () {
  607. var hash = this.x || 0;
  608. hash = (hash * 397) ^ (this.y || 0);
  609. hash = (hash * 397) ^ (this.z || 0);
  610. return hash;
  611. };
  612. // Operators
  613. Vector3.prototype.asArray = function () {
  614. var result = [];
  615. this.toArray(result, 0);
  616. return result;
  617. };
  618. Vector3.prototype.toArray = function (array, index) {
  619. if (index === void 0) { index = 0; }
  620. array[index] = this.x;
  621. array[index + 1] = this.y;
  622. array[index + 2] = this.z;
  623. return this;
  624. };
  625. Vector3.prototype.toQuaternion = function () {
  626. var result = new Quaternion(0, 0, 0, 1);
  627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  631. var cosy = Math.cos(this.y * 0.5);
  632. var siny = Math.sin(this.y * 0.5);
  633. result.x = coszMinusx * siny;
  634. result.y = -sinzMinusx * siny;
  635. result.z = sinxPlusz * cosy;
  636. result.w = cosxPlusz * cosy;
  637. return result;
  638. };
  639. Vector3.prototype.addInPlace = function (otherVector) {
  640. this.x += otherVector.x;
  641. this.y += otherVector.y;
  642. this.z += otherVector.z;
  643. return this;
  644. };
  645. Vector3.prototype.add = function (otherVector) {
  646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  647. };
  648. Vector3.prototype.addToRef = function (otherVector, result) {
  649. result.x = this.x + otherVector.x;
  650. result.y = this.y + otherVector.y;
  651. result.z = this.z + otherVector.z;
  652. return this;
  653. };
  654. Vector3.prototype.subtractInPlace = function (otherVector) {
  655. this.x -= otherVector.x;
  656. this.y -= otherVector.y;
  657. this.z -= otherVector.z;
  658. return this;
  659. };
  660. Vector3.prototype.subtract = function (otherVector) {
  661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  662. };
  663. Vector3.prototype.subtractToRef = function (otherVector, result) {
  664. result.x = this.x - otherVector.x;
  665. result.y = this.y - otherVector.y;
  666. result.z = this.z - otherVector.z;
  667. return this;
  668. };
  669. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  670. return new Vector3(this.x - x, this.y - y, this.z - z);
  671. };
  672. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  673. result.x = this.x - x;
  674. result.y = this.y - y;
  675. result.z = this.z - z;
  676. return this;
  677. };
  678. Vector3.prototype.negate = function () {
  679. return new Vector3(-this.x, -this.y, -this.z);
  680. };
  681. Vector3.prototype.scaleInPlace = function (scale) {
  682. this.x *= scale;
  683. this.y *= scale;
  684. this.z *= scale;
  685. return this;
  686. };
  687. Vector3.prototype.scale = function (scale) {
  688. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  689. };
  690. Vector3.prototype.scaleToRef = function (scale, result) {
  691. result.x = this.x * scale;
  692. result.y = this.y * scale;
  693. result.z = this.z * scale;
  694. };
  695. Vector3.prototype.equals = function (otherVector) {
  696. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  697. };
  698. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  699. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  700. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  701. };
  702. Vector3.prototype.equalsToFloats = function (x, y, z) {
  703. return this.x === x && this.y === y && this.z === z;
  704. };
  705. Vector3.prototype.multiplyInPlace = function (otherVector) {
  706. this.x *= otherVector.x;
  707. this.y *= otherVector.y;
  708. this.z *= otherVector.z;
  709. return this;
  710. };
  711. Vector3.prototype.multiply = function (otherVector) {
  712. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  713. };
  714. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  715. result.x = this.x * otherVector.x;
  716. result.y = this.y * otherVector.y;
  717. result.z = this.z * otherVector.z;
  718. return this;
  719. };
  720. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  721. return new Vector3(this.x * x, this.y * y, this.z * z);
  722. };
  723. Vector3.prototype.divide = function (otherVector) {
  724. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  725. };
  726. Vector3.prototype.divideToRef = function (otherVector, result) {
  727. result.x = this.x / otherVector.x;
  728. result.y = this.y / otherVector.y;
  729. result.z = this.z / otherVector.z;
  730. return this;
  731. };
  732. Vector3.prototype.MinimizeInPlace = function (other) {
  733. if (other.x < this.x)
  734. this.x = other.x;
  735. if (other.y < this.y)
  736. this.y = other.y;
  737. if (other.z < this.z)
  738. this.z = other.z;
  739. return this;
  740. };
  741. Vector3.prototype.MaximizeInPlace = function (other) {
  742. if (other.x > this.x)
  743. this.x = other.x;
  744. if (other.y > this.y)
  745. this.y = other.y;
  746. if (other.z > this.z)
  747. this.z = other.z;
  748. return this;
  749. };
  750. // Properties
  751. Vector3.prototype.length = function () {
  752. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  753. };
  754. Vector3.prototype.lengthSquared = function () {
  755. return (this.x * this.x + this.y * this.y + this.z * this.z);
  756. };
  757. // Methods
  758. Vector3.prototype.normalize = function () {
  759. var len = this.length();
  760. if (len === 0 || len === 1.0)
  761. return this;
  762. var num = 1.0 / len;
  763. this.x *= num;
  764. this.y *= num;
  765. this.z *= num;
  766. return this;
  767. };
  768. Vector3.prototype.clone = function () {
  769. return new Vector3(this.x, this.y, this.z);
  770. };
  771. Vector3.prototype.copyFrom = function (source) {
  772. this.x = source.x;
  773. this.y = source.y;
  774. this.z = source.z;
  775. return this;
  776. };
  777. Vector3.prototype.copyFromFloats = function (x, y, z) {
  778. this.x = x;
  779. this.y = y;
  780. this.z = z;
  781. return this;
  782. };
  783. // Statics
  784. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  785. var d0 = Vector3.Dot(vector0, axis) - size;
  786. var d1 = Vector3.Dot(vector1, axis) - size;
  787. var s = d0 / (d0 - d1);
  788. return s;
  789. };
  790. Vector3.FromArray = function (array, offset) {
  791. if (!offset) {
  792. offset = 0;
  793. }
  794. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  795. };
  796. Vector3.FromFloatArray = function (array, offset) {
  797. if (!offset) {
  798. offset = 0;
  799. }
  800. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  801. };
  802. Vector3.FromArrayToRef = function (array, offset, result) {
  803. result.x = array[offset];
  804. result.y = array[offset + 1];
  805. result.z = array[offset + 2];
  806. };
  807. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  808. result.x = array[offset];
  809. result.y = array[offset + 1];
  810. result.z = array[offset + 2];
  811. };
  812. Vector3.FromFloatsToRef = function (x, y, z, result) {
  813. result.x = x;
  814. result.y = y;
  815. result.z = z;
  816. };
  817. Vector3.Zero = function () {
  818. return new Vector3(0, 0, 0);
  819. };
  820. Vector3.Up = function () {
  821. return new Vector3(0, 1.0, 0);
  822. };
  823. Vector3.TransformCoordinates = function (vector, transformation) {
  824. var result = Vector3.Zero();
  825. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  826. return result;
  827. };
  828. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  829. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  830. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  831. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  832. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  833. result.x = x / w;
  834. result.y = y / w;
  835. result.z = z / w;
  836. };
  837. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  838. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  839. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  840. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  841. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  842. result.x = rx / rw;
  843. result.y = ry / rw;
  844. result.z = rz / rw;
  845. };
  846. Vector3.TransformNormal = function (vector, transformation) {
  847. var result = Vector3.Zero();
  848. Vector3.TransformNormalToRef(vector, transformation, result);
  849. return result;
  850. };
  851. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  852. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  853. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  854. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  855. };
  856. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  857. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  858. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  859. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  860. };
  861. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  865. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  866. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  867. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  868. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  869. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  870. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  871. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  872. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  873. return new Vector3(x, y, z);
  874. };
  875. Vector3.Clamp = function (value, min, max) {
  876. var x = value.x;
  877. x = (x > max.x) ? max.x : x;
  878. x = (x < min.x) ? min.x : x;
  879. var y = value.y;
  880. y = (y > max.y) ? max.y : y;
  881. y = (y < min.y) ? min.y : y;
  882. var z = value.z;
  883. z = (z > max.z) ? max.z : z;
  884. z = (z < min.z) ? min.z : z;
  885. return new Vector3(x, y, z);
  886. };
  887. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  888. var squared = amount * amount;
  889. var cubed = amount * squared;
  890. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  891. var part2 = (-2.0 * cubed) + (3.0 * squared);
  892. var part3 = (cubed - (2.0 * squared)) + amount;
  893. var part4 = cubed - squared;
  894. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  895. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  896. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  897. return new Vector3(x, y, z);
  898. };
  899. Vector3.Lerp = function (start, end, amount) {
  900. var x = start.x + ((end.x - start.x) * amount);
  901. var y = start.y + ((end.y - start.y) * amount);
  902. var z = start.z + ((end.z - start.z) * amount);
  903. return new Vector3(x, y, z);
  904. };
  905. Vector3.Dot = function (left, right) {
  906. return (left.x * right.x + left.y * right.y + left.z * right.z);
  907. };
  908. Vector3.Cross = function (left, right) {
  909. var result = Vector3.Zero();
  910. Vector3.CrossToRef(left, right, result);
  911. return result;
  912. };
  913. Vector3.CrossToRef = function (left, right, result) {
  914. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  915. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  916. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  917. result.copyFrom(Tmp.Vector3[0]);
  918. };
  919. Vector3.Normalize = function (vector) {
  920. var result = Vector3.Zero();
  921. Vector3.NormalizeToRef(vector, result);
  922. return result;
  923. };
  924. Vector3.NormalizeToRef = function (vector, result) {
  925. result.copyFrom(vector);
  926. result.normalize();
  927. };
  928. Vector3.Project = function (vector, world, transform, viewport) {
  929. var cw = viewport.width;
  930. var ch = viewport.height;
  931. var cx = viewport.x;
  932. var cy = viewport.y;
  933. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  934. 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);
  935. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  936. world.multiplyToRef(transform, matrix);
  937. matrix.multiplyToRef(viewportMatrix, matrix);
  938. return Vector3.TransformCoordinates(vector, matrix);
  939. };
  940. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  941. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  942. world.multiplyToRef(transform, matrix);
  943. matrix.invert();
  944. source.x = source.x / viewportWidth * 2 - 1;
  945. source.y = -(source.y / viewportHeight * 2 - 1);
  946. var vector = Vector3.TransformCoordinates(source, matrix);
  947. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  948. if (MathTools.WithinEpsilon(num, 1.0)) {
  949. vector = vector.scale(1.0 / num);
  950. }
  951. return vector;
  952. };
  953. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  954. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  955. world.multiplyToRef(view, matrix);
  956. matrix.multiplyToRef(projection, matrix);
  957. matrix.invert();
  958. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  959. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  960. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  961. if (MathTools.WithinEpsilon(num, 1.0)) {
  962. vector = vector.scale(1.0 / num);
  963. }
  964. return vector;
  965. };
  966. Vector3.Minimize = function (left, right) {
  967. var min = left.clone();
  968. min.MinimizeInPlace(right);
  969. return min;
  970. };
  971. Vector3.Maximize = function (left, right) {
  972. var max = left.clone();
  973. max.MaximizeInPlace(right);
  974. return max;
  975. };
  976. Vector3.Distance = function (value1, value2) {
  977. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  978. };
  979. Vector3.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. var z = value1.z - value2.z;
  983. return (x * x) + (y * y) + (z * z);
  984. };
  985. Vector3.Center = function (value1, value2) {
  986. var center = value1.add(value2);
  987. center.scaleInPlace(0.5);
  988. return center;
  989. };
  990. /**
  991. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  992. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  993. * to something in order to rotate it from its local system to the given target system.
  994. */
  995. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  996. var rotation = Vector3.Zero();
  997. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  998. return rotation;
  999. };
  1000. /**
  1001. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1002. */
  1003. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1004. var u = axis1.normalize();
  1005. var w = axis3.normalize();
  1006. // world axis
  1007. var X = Axis.X;
  1008. var Y = Axis.Y;
  1009. // equation unknowns and vars
  1010. var yaw = 0.0;
  1011. var pitch = 0.0;
  1012. var roll = 0.0;
  1013. var x = 0.0;
  1014. var y = 0.0;
  1015. var z = 0.0;
  1016. var t = 0.0;
  1017. var sign = -1.0;
  1018. var nbRevert = 0;
  1019. var cross = Tmp.Vector3[0];
  1020. var dot = 0.0;
  1021. // step 1 : rotation around w
  1022. // Rv3(u) = u1, and u1 belongs to plane xOz
  1023. // Rv3(w) = w1 = w invariant
  1024. var u1 = Tmp.Vector3[1];
  1025. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1026. z = 1.0;
  1027. }
  1028. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1029. x = 1.0;
  1030. }
  1031. else {
  1032. t = w.z / w.x;
  1033. x = -t * Math.sqrt(1 / (1 + t * t));
  1034. z = Math.sqrt(1 / (1 + t * t));
  1035. }
  1036. u1.x = x;
  1037. u1.y = y;
  1038. u1.z = z;
  1039. u1.normalize();
  1040. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1041. cross.normalize();
  1042. if (Vector3.Dot(w, cross) < 0) {
  1043. sign = 1.0;
  1044. }
  1045. dot = Vector3.Dot(u, u1);
  1046. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1047. roll = Math.acos(dot) * sign;
  1048. if (Vector3.Dot(u1, X) < 0) {
  1049. roll = Math.PI + roll;
  1050. u1 = u1.scaleInPlace(-1);
  1051. nbRevert++;
  1052. }
  1053. // step 2 : rotate around u1
  1054. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1055. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1056. var w2 = Tmp.Vector3[2];
  1057. var v2 = Tmp.Vector3[3];
  1058. x = 0.0;
  1059. y = 0.0;
  1060. z = 0.0;
  1061. sign = -1.0;
  1062. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1063. x = 1.0;
  1064. }
  1065. else {
  1066. t = u1.z / u1.x;
  1067. x = -t * Math.sqrt(1 / (1 + t * t));
  1068. z = Math.sqrt(1 / (1 + t * t));
  1069. }
  1070. w2.x = x;
  1071. w2.y = y;
  1072. w2.z = z;
  1073. w2.normalize();
  1074. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1075. v2.normalize();
  1076. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1077. cross.normalize();
  1078. if (Vector3.Dot(u1, cross) < 0) {
  1079. sign = 1.0;
  1080. }
  1081. dot = Vector3.Dot(w, w2);
  1082. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1083. pitch = Math.acos(dot) * sign;
  1084. if (Vector3.Dot(v2, Y) < 0) {
  1085. pitch = Math.PI + pitch;
  1086. nbRevert++;
  1087. }
  1088. // step 3 : rotate around v2
  1089. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1090. sign = -1.0;
  1091. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1092. cross.normalize();
  1093. if (Vector3.Dot(cross, Y) < 0) {
  1094. sign = 1.0;
  1095. }
  1096. dot = Vector3.Dot(u1, X);
  1097. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1098. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1099. if (dot < 0 && nbRevert < 2) {
  1100. yaw = Math.PI + yaw;
  1101. }
  1102. ref.x = pitch;
  1103. ref.y = yaw;
  1104. ref.z = roll;
  1105. };
  1106. return Vector3;
  1107. })();
  1108. BABYLON.Vector3 = Vector3;
  1109. //Vector4 class created for EulerAngle class conversion to Quaternion
  1110. var Vector4 = (function () {
  1111. function Vector4(x, y, z, w) {
  1112. this.x = x;
  1113. this.y = y;
  1114. this.z = z;
  1115. this.w = w;
  1116. }
  1117. Vector4.prototype.toString = function () {
  1118. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1119. };
  1120. Vector4.prototype.getClassName = function () {
  1121. return "Vector4";
  1122. };
  1123. Vector4.prototype.getHashCode = function () {
  1124. var hash = this.x || 0;
  1125. hash = (hash * 397) ^ (this.y || 0);
  1126. hash = (hash * 397) ^ (this.z || 0);
  1127. hash = (hash * 397) ^ (this.w || 0);
  1128. return hash;
  1129. };
  1130. // Operators
  1131. Vector4.prototype.asArray = function () {
  1132. var result = [];
  1133. this.toArray(result, 0);
  1134. return result;
  1135. };
  1136. Vector4.prototype.toArray = function (array, index) {
  1137. if (index === undefined) {
  1138. index = 0;
  1139. }
  1140. array[index] = this.x;
  1141. array[index + 1] = this.y;
  1142. array[index + 2] = this.z;
  1143. array[index + 3] = this.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.addInPlace = function (otherVector) {
  1147. this.x += otherVector.x;
  1148. this.y += otherVector.y;
  1149. this.z += otherVector.z;
  1150. this.w += otherVector.w;
  1151. return this;
  1152. };
  1153. Vector4.prototype.add = function (otherVector) {
  1154. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1155. };
  1156. Vector4.prototype.addToRef = function (otherVector, result) {
  1157. result.x = this.x + otherVector.x;
  1158. result.y = this.y + otherVector.y;
  1159. result.z = this.z + otherVector.z;
  1160. result.w = this.w + otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.subtractInPlace = function (otherVector) {
  1164. this.x -= otherVector.x;
  1165. this.y -= otherVector.y;
  1166. this.z -= otherVector.z;
  1167. this.w -= otherVector.w;
  1168. return this;
  1169. };
  1170. Vector4.prototype.subtract = function (otherVector) {
  1171. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1172. };
  1173. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1174. result.x = this.x - otherVector.x;
  1175. result.y = this.y - otherVector.y;
  1176. result.z = this.z - otherVector.z;
  1177. result.w = this.w - otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1181. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1182. };
  1183. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1184. result.x = this.x - x;
  1185. result.y = this.y - y;
  1186. result.z = this.z - z;
  1187. result.w = this.w - w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.negate = function () {
  1191. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1192. };
  1193. Vector4.prototype.scaleInPlace = function (scale) {
  1194. this.x *= scale;
  1195. this.y *= scale;
  1196. this.z *= scale;
  1197. this.w *= scale;
  1198. return this;
  1199. };
  1200. Vector4.prototype.scale = function (scale) {
  1201. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1202. };
  1203. Vector4.prototype.scaleToRef = function (scale, result) {
  1204. result.x = this.x * scale;
  1205. result.y = this.y * scale;
  1206. result.z = this.z * scale;
  1207. result.w = this.w * scale;
  1208. };
  1209. Vector4.prototype.equals = function (otherVector) {
  1210. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1211. };
  1212. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1213. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1214. return otherVector
  1215. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1216. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1217. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1218. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1219. };
  1220. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1221. return this.x === x && this.y === y && this.z === z && this.w === w;
  1222. };
  1223. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1224. this.x *= otherVector.x;
  1225. this.y *= otherVector.y;
  1226. this.z *= otherVector.z;
  1227. this.w *= otherVector.w;
  1228. return this;
  1229. };
  1230. Vector4.prototype.multiply = function (otherVector) {
  1231. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1232. };
  1233. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1234. result.x = this.x * otherVector.x;
  1235. result.y = this.y * otherVector.y;
  1236. result.z = this.z * otherVector.z;
  1237. result.w = this.w * otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1241. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1242. };
  1243. Vector4.prototype.divide = function (otherVector) {
  1244. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1245. };
  1246. Vector4.prototype.divideToRef = function (otherVector, result) {
  1247. result.x = this.x / otherVector.x;
  1248. result.y = this.y / otherVector.y;
  1249. result.z = this.z / otherVector.z;
  1250. result.w = this.w / otherVector.w;
  1251. return this;
  1252. };
  1253. Vector4.prototype.MinimizeInPlace = function (other) {
  1254. if (other.x < this.x)
  1255. this.x = other.x;
  1256. if (other.y < this.y)
  1257. this.y = other.y;
  1258. if (other.z < this.z)
  1259. this.z = other.z;
  1260. if (other.w < this.w)
  1261. this.w = other.w;
  1262. return this;
  1263. };
  1264. Vector4.prototype.MaximizeInPlace = function (other) {
  1265. if (other.x > this.x)
  1266. this.x = other.x;
  1267. if (other.y > this.y)
  1268. this.y = other.y;
  1269. if (other.z > this.z)
  1270. this.z = other.z;
  1271. if (other.w > this.w)
  1272. this.w = other.w;
  1273. return this;
  1274. };
  1275. // Properties
  1276. Vector4.prototype.length = function () {
  1277. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1278. };
  1279. Vector4.prototype.lengthSquared = function () {
  1280. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1281. };
  1282. // Methods
  1283. Vector4.prototype.normalize = function () {
  1284. var len = this.length();
  1285. if (len === 0)
  1286. return this;
  1287. var num = 1.0 / len;
  1288. this.x *= num;
  1289. this.y *= num;
  1290. this.z *= num;
  1291. this.w *= num;
  1292. return this;
  1293. };
  1294. Vector4.prototype.toVector3 = function () {
  1295. return new Vector3(this.x, this.y, this.z);
  1296. };
  1297. Vector4.prototype.clone = function () {
  1298. return new Vector4(this.x, this.y, this.z, this.w);
  1299. };
  1300. Vector4.prototype.copyFrom = function (source) {
  1301. this.x = source.x;
  1302. this.y = source.y;
  1303. this.z = source.z;
  1304. this.w = source.w;
  1305. return this;
  1306. };
  1307. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1308. this.x = x;
  1309. this.y = y;
  1310. this.z = z;
  1311. this.w = w;
  1312. return this;
  1313. };
  1314. // Statics
  1315. Vector4.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1320. };
  1321. Vector4.FromArrayToRef = function (array, offset, result) {
  1322. result.x = array[offset];
  1323. result.y = array[offset + 1];
  1324. result.z = array[offset + 2];
  1325. result.w = array[offset + 3];
  1326. };
  1327. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1328. result.x = array[offset];
  1329. result.y = array[offset + 1];
  1330. result.z = array[offset + 2];
  1331. result.w = array[offset + 3];
  1332. };
  1333. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1334. result.x = x;
  1335. result.y = y;
  1336. result.z = z;
  1337. result.w = w;
  1338. };
  1339. Vector4.Zero = function () {
  1340. return new Vector4(0, 0, 0, 0);
  1341. };
  1342. Vector4.Normalize = function (vector) {
  1343. var result = Vector4.Zero();
  1344. Vector4.NormalizeToRef(vector, result);
  1345. return result;
  1346. };
  1347. Vector4.NormalizeToRef = function (vector, result) {
  1348. result.copyFrom(vector);
  1349. result.normalize();
  1350. };
  1351. Vector4.Minimize = function (left, right) {
  1352. var min = left.clone();
  1353. min.MinimizeInPlace(right);
  1354. return min;
  1355. };
  1356. Vector4.Maximize = function (left, right) {
  1357. var max = left.clone();
  1358. max.MaximizeInPlace(right);
  1359. return max;
  1360. };
  1361. Vector4.Distance = function (value1, value2) {
  1362. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1363. };
  1364. Vector4.DistanceSquared = function (value1, value2) {
  1365. var x = value1.x - value2.x;
  1366. var y = value1.y - value2.y;
  1367. var z = value1.z - value2.z;
  1368. var w = value1.w - value2.w;
  1369. return (x * x) + (y * y) + (z * z) + (w * w);
  1370. };
  1371. Vector4.Center = function (value1, value2) {
  1372. var center = value1.add(value2);
  1373. center.scaleInPlace(0.5);
  1374. return center;
  1375. };
  1376. return Vector4;
  1377. })();
  1378. BABYLON.Vector4 = Vector4;
  1379. var Size = (function () {
  1380. function Size(width, height) {
  1381. this.width = width;
  1382. this.height = height;
  1383. }
  1384. Size.prototype.toString = function () {
  1385. return "{W: " + this.width + ", H: " + this.height + "}";
  1386. };
  1387. Size.prototype.getClassName = function () {
  1388. return "Size";
  1389. };
  1390. Size.prototype.getHashCode = function () {
  1391. var hash = this.width || 0;
  1392. hash = (hash * 397) ^ (this.height || 0);
  1393. return hash;
  1394. };
  1395. Size.prototype.copyFrom = function (src) {
  1396. this.width = src.width;
  1397. this.height = src.height;
  1398. };
  1399. Size.prototype.copyFromFloats = function (width, height) {
  1400. this.width = width;
  1401. this.height = height;
  1402. };
  1403. Size.prototype.multiplyByFloats = function (w, h) {
  1404. return new Size(this.width * w, this.height * h);
  1405. };
  1406. Size.prototype.clone = function () {
  1407. return new Size(this.width, this.height);
  1408. };
  1409. Size.prototype.equals = function (other) {
  1410. if (!other) {
  1411. return false;
  1412. }
  1413. return (this.width === other.width) && (this.height === other.height);
  1414. };
  1415. Object.defineProperty(Size.prototype, "surface", {
  1416. get: function () {
  1417. return this.width * this.height;
  1418. },
  1419. enumerable: true,
  1420. configurable: true
  1421. });
  1422. Size.Zero = function () {
  1423. return new Size(0, 0);
  1424. };
  1425. Size.prototype.add = function (otherSize) {
  1426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1427. return r;
  1428. };
  1429. Size.prototype.substract = function (otherSize) {
  1430. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1431. return r;
  1432. };
  1433. Size.Lerp = function (start, end, amount) {
  1434. var w = start.width + ((end.width - start.width) * amount);
  1435. var h = start.height + ((end.height - start.height) * amount);
  1436. return new Size(w, h);
  1437. };
  1438. return Size;
  1439. })();
  1440. BABYLON.Size = Size;
  1441. var Quaternion = (function () {
  1442. function Quaternion(x, y, z, w) {
  1443. if (x === void 0) { x = 0; }
  1444. if (y === void 0) { y = 0; }
  1445. if (z === void 0) { z = 0; }
  1446. if (w === void 0) { w = 1; }
  1447. this.x = x;
  1448. this.y = y;
  1449. this.z = z;
  1450. this.w = w;
  1451. }
  1452. Quaternion.prototype.toString = function () {
  1453. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1454. };
  1455. Quaternion.prototype.getClassName = function () {
  1456. return "Quaternion";
  1457. };
  1458. Quaternion.prototype.getHashCode = function () {
  1459. var hash = this.x || 0;
  1460. hash = (hash * 397) ^ (this.y || 0);
  1461. hash = (hash * 397) ^ (this.z || 0);
  1462. hash = (hash * 397) ^ (this.w || 0);
  1463. return hash;
  1464. };
  1465. Quaternion.prototype.asArray = function () {
  1466. return [this.x, this.y, this.z, this.w];
  1467. };
  1468. Quaternion.prototype.equals = function (otherQuaternion) {
  1469. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1470. };
  1471. Quaternion.prototype.clone = function () {
  1472. return new Quaternion(this.x, this.y, this.z, this.w);
  1473. };
  1474. Quaternion.prototype.copyFrom = function (other) {
  1475. this.x = other.x;
  1476. this.y = other.y;
  1477. this.z = other.z;
  1478. this.w = other.w;
  1479. return this;
  1480. };
  1481. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1482. this.x = x;
  1483. this.y = y;
  1484. this.z = z;
  1485. this.w = w;
  1486. return this;
  1487. };
  1488. Quaternion.prototype.add = function (other) {
  1489. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1490. };
  1491. Quaternion.prototype.subtract = function (other) {
  1492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1493. };
  1494. Quaternion.prototype.scale = function (value) {
  1495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1496. };
  1497. Quaternion.prototype.multiply = function (q1) {
  1498. var result = new Quaternion(0, 0, 0, 1.0);
  1499. this.multiplyToRef(q1, result);
  1500. return result;
  1501. };
  1502. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1503. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1504. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1505. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1506. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1507. result.copyFromFloats(x, y, z, w);
  1508. return this;
  1509. };
  1510. Quaternion.prototype.multiplyInPlace = function (q1) {
  1511. this.multiplyToRef(q1, this);
  1512. return this;
  1513. };
  1514. Quaternion.prototype.conjugateToRef = function (ref) {
  1515. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1516. return this;
  1517. };
  1518. Quaternion.prototype.conjugateInPlace = function () {
  1519. this.x *= -1;
  1520. this.y *= -1;
  1521. this.z *= -1;
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugate = function () {
  1525. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.length = function () {
  1529. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1530. };
  1531. Quaternion.prototype.normalize = function () {
  1532. var length = 1.0 / this.length();
  1533. this.x *= length;
  1534. this.y *= length;
  1535. this.z *= length;
  1536. this.w *= length;
  1537. return this;
  1538. };
  1539. Quaternion.prototype.toEulerAngles = function (order) {
  1540. if (order === void 0) { order = "YZX"; }
  1541. var result = Vector3.Zero();
  1542. this.toEulerAnglesToRef(result, order);
  1543. return result;
  1544. };
  1545. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1546. if (order === void 0) { order = "YZX"; }
  1547. var heading, attitude, bank;
  1548. var x = this.x, y = this.y, z = this.z, w = this.w;
  1549. switch (order) {
  1550. case "YZX":
  1551. var test = x * y + z * w;
  1552. if (test > 0.499) {
  1553. heading = 2 * Math.atan2(x, w);
  1554. attitude = Math.PI / 2;
  1555. bank = 0;
  1556. }
  1557. if (test < -0.499) {
  1558. heading = -2 * Math.atan2(x, w);
  1559. attitude = -Math.PI / 2;
  1560. bank = 0;
  1561. }
  1562. if (isNaN(heading)) {
  1563. var sqx = x * x;
  1564. var sqy = y * y;
  1565. var sqz = z * z;
  1566. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1567. attitude = Math.asin(2 * test); // attitude
  1568. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1569. }
  1570. break;
  1571. default:
  1572. throw new Error("Euler order " + order + " not supported yet.");
  1573. }
  1574. result.y = heading;
  1575. result.z = attitude;
  1576. result.x = bank;
  1577. return this;
  1578. };
  1579. ;
  1580. Quaternion.prototype.toRotationMatrix = function (result) {
  1581. var xx = this.x * this.x;
  1582. var yy = this.y * this.y;
  1583. var zz = this.z * this.z;
  1584. var xy = this.x * this.y;
  1585. var zw = this.z * this.w;
  1586. var zx = this.z * this.x;
  1587. var yw = this.y * this.w;
  1588. var yz = this.y * this.z;
  1589. var xw = this.x * this.w;
  1590. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1591. result.m[1] = 2.0 * (xy + zw);
  1592. result.m[2] = 2.0 * (zx - yw);
  1593. result.m[3] = 0;
  1594. result.m[4] = 2.0 * (xy - zw);
  1595. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1596. result.m[6] = 2.0 * (yz + xw);
  1597. result.m[7] = 0;
  1598. result.m[8] = 2.0 * (zx + yw);
  1599. result.m[9] = 2.0 * (yz - xw);
  1600. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1601. result.m[11] = 0;
  1602. result.m[12] = 0;
  1603. result.m[13] = 0;
  1604. result.m[14] = 0;
  1605. result.m[15] = 1.0;
  1606. return this;
  1607. };
  1608. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1609. Quaternion.FromRotationMatrixToRef(matrix, this);
  1610. return this;
  1611. };
  1612. // Statics
  1613. Quaternion.FromRotationMatrix = function (matrix) {
  1614. var result = new Quaternion();
  1615. Quaternion.FromRotationMatrixToRef(matrix, result);
  1616. return result;
  1617. };
  1618. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1619. var data = matrix.m;
  1620. var m11 = data[0], m12 = data[4], m13 = data[8];
  1621. var m21 = data[1], m22 = data[5], m23 = data[9];
  1622. var m31 = data[2], m32 = data[6], m33 = data[10];
  1623. var trace = m11 + m22 + m33;
  1624. var s;
  1625. if (trace > 0) {
  1626. s = 0.5 / Math.sqrt(trace + 1.0);
  1627. result.w = 0.25 / s;
  1628. result.x = (m32 - m23) * s;
  1629. result.y = (m13 - m31) * s;
  1630. result.z = (m21 - m12) * s;
  1631. }
  1632. else if (m11 > m22 && m11 > m33) {
  1633. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1634. result.w = (m32 - m23) / s;
  1635. result.x = 0.25 * s;
  1636. result.y = (m12 + m21) / s;
  1637. result.z = (m13 + m31) / s;
  1638. }
  1639. else if (m22 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1641. result.w = (m13 - m31) / s;
  1642. result.x = (m12 + m21) / s;
  1643. result.y = 0.25 * s;
  1644. result.z = (m23 + m32) / s;
  1645. }
  1646. else {
  1647. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1648. result.w = (m21 - m12) / s;
  1649. result.x = (m13 + m31) / s;
  1650. result.y = (m23 + m32) / s;
  1651. result.z = 0.25 * s;
  1652. }
  1653. };
  1654. Quaternion.Inverse = function (q) {
  1655. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1656. };
  1657. Quaternion.Identity = function () {
  1658. return new Quaternion(0, 0, 0, 1);
  1659. };
  1660. Quaternion.RotationAxis = function (axis, angle) {
  1661. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1662. };
  1663. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1664. var sin = Math.sin(angle / 2);
  1665. axis.normalize();
  1666. result.w = Math.cos(angle / 2);
  1667. result.x = axis.x * sin;
  1668. result.y = axis.y * sin;
  1669. result.z = axis.z * sin;
  1670. return result;
  1671. };
  1672. Quaternion.FromArray = function (array, offset) {
  1673. if (!offset) {
  1674. offset = 0;
  1675. }
  1676. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1677. };
  1678. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1679. var q = new Quaternion();
  1680. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1681. return q;
  1682. };
  1683. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1684. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1685. var halfRoll = roll * 0.5;
  1686. var halfPitch = pitch * 0.5;
  1687. var halfYaw = yaw * 0.5;
  1688. var sinRoll = Math.sin(halfRoll);
  1689. var cosRoll = Math.cos(halfRoll);
  1690. var sinPitch = Math.sin(halfPitch);
  1691. var cosPitch = Math.cos(halfPitch);
  1692. var sinYaw = Math.sin(halfYaw);
  1693. var cosYaw = Math.cos(halfYaw);
  1694. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1695. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1696. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1697. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1698. };
  1699. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1700. var result = new Quaternion();
  1701. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1702. return result;
  1703. };
  1704. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1705. // Produces a quaternion from Euler angles in the z-x-z orientation
  1706. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1707. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1708. var halfBeta = beta * 0.5;
  1709. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1710. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1711. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1712. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1713. };
  1714. Quaternion.Slerp = function (left, right, amount) {
  1715. var num2;
  1716. var num3;
  1717. var num = amount;
  1718. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1719. var flag = false;
  1720. if (num4 < 0) {
  1721. flag = true;
  1722. num4 = -num4;
  1723. }
  1724. if (num4 > 0.999999) {
  1725. num3 = 1 - num;
  1726. num2 = flag ? -num : num;
  1727. }
  1728. else {
  1729. var num5 = Math.acos(num4);
  1730. var num6 = (1.0 / Math.sin(num5));
  1731. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1732. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1733. }
  1734. 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));
  1735. };
  1736. return Quaternion;
  1737. })();
  1738. BABYLON.Quaternion = Quaternion;
  1739. var Matrix = (function () {
  1740. function Matrix() {
  1741. this.m = new Float32Array(16);
  1742. }
  1743. // Properties
  1744. Matrix.prototype.isIdentity = function () {
  1745. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1746. return false;
  1747. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1751. return false;
  1752. return true;
  1753. };
  1754. Matrix.prototype.determinant = function () {
  1755. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1756. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1757. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1758. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1759. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1760. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1761. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1762. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1763. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1764. };
  1765. // Methods
  1766. Matrix.prototype.toArray = function () {
  1767. return this.m;
  1768. };
  1769. Matrix.prototype.asArray = function () {
  1770. return this.toArray();
  1771. };
  1772. Matrix.prototype.invert = function () {
  1773. this.invertToRef(this);
  1774. return this;
  1775. };
  1776. Matrix.prototype.reset = function () {
  1777. for (var index = 0; index < 16; index++) {
  1778. this.m[index] = 0;
  1779. }
  1780. return this;
  1781. };
  1782. Matrix.prototype.add = function (other) {
  1783. var result = new Matrix();
  1784. this.addToRef(other, result);
  1785. return result;
  1786. };
  1787. Matrix.prototype.addToRef = function (other, result) {
  1788. for (var index = 0; index < 16; index++) {
  1789. result.m[index] = this.m[index] + other.m[index];
  1790. }
  1791. return this;
  1792. };
  1793. Matrix.prototype.addToSelf = function (other) {
  1794. for (var index = 0; index < 16; index++) {
  1795. this.m[index] += other.m[index];
  1796. }
  1797. return this;
  1798. };
  1799. Matrix.prototype.invertToRef = function (other) {
  1800. var l1 = this.m[0];
  1801. var l2 = this.m[1];
  1802. var l3 = this.m[2];
  1803. var l4 = this.m[3];
  1804. var l5 = this.m[4];
  1805. var l6 = this.m[5];
  1806. var l7 = this.m[6];
  1807. var l8 = this.m[7];
  1808. var l9 = this.m[8];
  1809. var l10 = this.m[9];
  1810. var l11 = this.m[10];
  1811. var l12 = this.m[11];
  1812. var l13 = this.m[12];
  1813. var l14 = this.m[13];
  1814. var l15 = this.m[14];
  1815. var l16 = this.m[15];
  1816. var l17 = (l11 * l16) - (l12 * l15);
  1817. var l18 = (l10 * l16) - (l12 * l14);
  1818. var l19 = (l10 * l15) - (l11 * l14);
  1819. var l20 = (l9 * l16) - (l12 * l13);
  1820. var l21 = (l9 * l15) - (l11 * l13);
  1821. var l22 = (l9 * l14) - (l10 * l13);
  1822. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1823. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1824. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1825. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1826. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1827. var l28 = (l7 * l16) - (l8 * l15);
  1828. var l29 = (l6 * l16) - (l8 * l14);
  1829. var l30 = (l6 * l15) - (l7 * l14);
  1830. var l31 = (l5 * l16) - (l8 * l13);
  1831. var l32 = (l5 * l15) - (l7 * l13);
  1832. var l33 = (l5 * l14) - (l6 * l13);
  1833. var l34 = (l7 * l12) - (l8 * l11);
  1834. var l35 = (l6 * l12) - (l8 * l10);
  1835. var l36 = (l6 * l11) - (l7 * l10);
  1836. var l37 = (l5 * l12) - (l8 * l9);
  1837. var l38 = (l5 * l11) - (l7 * l9);
  1838. var l39 = (l5 * l10) - (l6 * l9);
  1839. other.m[0] = l23 * l27;
  1840. other.m[4] = l24 * l27;
  1841. other.m[8] = l25 * l27;
  1842. other.m[12] = l26 * l27;
  1843. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1844. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1845. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1846. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1847. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1848. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1849. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1850. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1851. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1852. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1853. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1854. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1855. return this;
  1856. };
  1857. Matrix.prototype.setTranslation = function (vector3) {
  1858. this.m[12] = vector3.x;
  1859. this.m[13] = vector3.y;
  1860. this.m[14] = vector3.z;
  1861. return this;
  1862. };
  1863. Matrix.prototype.getTranslation = function () {
  1864. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1865. };
  1866. Matrix.prototype.multiply = function (other) {
  1867. var result = new Matrix();
  1868. this.multiplyToRef(other, result);
  1869. return result;
  1870. };
  1871. Matrix.prototype.copyFrom = function (other) {
  1872. for (var index = 0; index < 16; index++) {
  1873. this.m[index] = other.m[index];
  1874. }
  1875. return this;
  1876. };
  1877. Matrix.prototype.copyToArray = function (array, offset) {
  1878. if (offset === void 0) { offset = 0; }
  1879. for (var index = 0; index < 16; index++) {
  1880. array[offset + index] = this.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.multiplyToRef = function (other, result) {
  1885. this.multiplyToArray(other, result.m, 0);
  1886. return this;
  1887. };
  1888. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1889. var tm0 = this.m[0];
  1890. var tm1 = this.m[1];
  1891. var tm2 = this.m[2];
  1892. var tm3 = this.m[3];
  1893. var tm4 = this.m[4];
  1894. var tm5 = this.m[5];
  1895. var tm6 = this.m[6];
  1896. var tm7 = this.m[7];
  1897. var tm8 = this.m[8];
  1898. var tm9 = this.m[9];
  1899. var tm10 = this.m[10];
  1900. var tm11 = this.m[11];
  1901. var tm12 = this.m[12];
  1902. var tm13 = this.m[13];
  1903. var tm14 = this.m[14];
  1904. var tm15 = this.m[15];
  1905. var om0 = other.m[0];
  1906. var om1 = other.m[1];
  1907. var om2 = other.m[2];
  1908. var om3 = other.m[3];
  1909. var om4 = other.m[4];
  1910. var om5 = other.m[5];
  1911. var om6 = other.m[6];
  1912. var om7 = other.m[7];
  1913. var om8 = other.m[8];
  1914. var om9 = other.m[9];
  1915. var om10 = other.m[10];
  1916. var om11 = other.m[11];
  1917. var om12 = other.m[12];
  1918. var om13 = other.m[13];
  1919. var om14 = other.m[14];
  1920. var om15 = other.m[15];
  1921. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1922. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1923. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1924. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1925. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1926. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1927. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1928. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1929. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1930. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1931. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1932. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1933. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1934. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1935. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1936. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1937. return this;
  1938. };
  1939. Matrix.prototype.equals = function (value) {
  1940. return value &&
  1941. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1942. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1943. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1944. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1945. };
  1946. Matrix.prototype.clone = function () {
  1947. 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]);
  1948. };
  1949. Matrix.prototype.getClassName = function () {
  1950. return "Matrix";
  1951. };
  1952. Matrix.prototype.getHashCode = function () {
  1953. var hash = this.m[0] || 0;
  1954. for (var i = 1; i < 16; i++) {
  1955. hash = (hash * 397) ^ (this.m[i] || 0);
  1956. }
  1957. return hash;
  1958. };
  1959. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1960. translation.x = this.m[12];
  1961. translation.y = this.m[13];
  1962. translation.z = this.m[14];
  1963. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1964. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1965. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1966. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1967. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1968. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1969. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1970. rotation.x = 0;
  1971. rotation.y = 0;
  1972. rotation.z = 0;
  1973. rotation.w = 1;
  1974. return false;
  1975. }
  1976. 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);
  1977. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1978. return true;
  1979. };
  1980. // Statics
  1981. Matrix.FromArray = function (array, offset) {
  1982. var result = new Matrix();
  1983. if (!offset) {
  1984. offset = 0;
  1985. }
  1986. Matrix.FromArrayToRef(array, offset, result);
  1987. return result;
  1988. };
  1989. Matrix.FromArrayToRef = function (array, offset, result) {
  1990. for (var index = 0; index < 16; index++) {
  1991. result.m[index] = array[index + offset];
  1992. }
  1993. };
  1994. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1995. for (var index = 0; index < 16; index++) {
  1996. result.m[index] = array[index + offset] * scale;
  1997. }
  1998. };
  1999. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2000. result.m[0] = initialM11;
  2001. result.m[1] = initialM12;
  2002. result.m[2] = initialM13;
  2003. result.m[3] = initialM14;
  2004. result.m[4] = initialM21;
  2005. result.m[5] = initialM22;
  2006. result.m[6] = initialM23;
  2007. result.m[7] = initialM24;
  2008. result.m[8] = initialM31;
  2009. result.m[9] = initialM32;
  2010. result.m[10] = initialM33;
  2011. result.m[11] = initialM34;
  2012. result.m[12] = initialM41;
  2013. result.m[13] = initialM42;
  2014. result.m[14] = initialM43;
  2015. result.m[15] = initialM44;
  2016. };
  2017. Matrix.prototype.getRow = function (index) {
  2018. if (index < 0 || index > 3) {
  2019. return null;
  2020. }
  2021. var i = index * 4;
  2022. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2023. };
  2024. Matrix.prototype.setRow = function (index, row) {
  2025. if (index < 0 || index > 3) {
  2026. return this;
  2027. }
  2028. var i = index * 4;
  2029. this.m[i + 0] = row.x;
  2030. this.m[i + 1] = row.y;
  2031. this.m[i + 2] = row.z;
  2032. this.m[i + 3] = row.w;
  2033. return this;
  2034. };
  2035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2036. var result = new Matrix();
  2037. result.m[0] = initialM11;
  2038. result.m[1] = initialM12;
  2039. result.m[2] = initialM13;
  2040. result.m[3] = initialM14;
  2041. result.m[4] = initialM21;
  2042. result.m[5] = initialM22;
  2043. result.m[6] = initialM23;
  2044. result.m[7] = initialM24;
  2045. result.m[8] = initialM31;
  2046. result.m[9] = initialM32;
  2047. result.m[10] = initialM33;
  2048. result.m[11] = initialM34;
  2049. result.m[12] = initialM41;
  2050. result.m[13] = initialM42;
  2051. result.m[14] = initialM43;
  2052. result.m[15] = initialM44;
  2053. return result;
  2054. };
  2055. Matrix.Compose = function (scale, rotation, translation) {
  2056. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2057. var rotationMatrix = Matrix.Identity();
  2058. rotation.toRotationMatrix(rotationMatrix);
  2059. result = result.multiply(rotationMatrix);
  2060. result.setTranslation(translation);
  2061. return result;
  2062. };
  2063. Matrix.Identity = function () {
  2064. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2065. };
  2066. Matrix.IdentityToRef = function (result) {
  2067. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2068. };
  2069. Matrix.Zero = function () {
  2070. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2071. };
  2072. Matrix.RotationX = function (angle) {
  2073. var result = new Matrix();
  2074. Matrix.RotationXToRef(angle, result);
  2075. return result;
  2076. };
  2077. Matrix.Invert = function (source) {
  2078. var result = new Matrix();
  2079. source.invertToRef(result);
  2080. return result;
  2081. };
  2082. Matrix.RotationXToRef = function (angle, result) {
  2083. var s = Math.sin(angle);
  2084. var c = Math.cos(angle);
  2085. result.m[0] = 1.0;
  2086. result.m[15] = 1.0;
  2087. result.m[5] = c;
  2088. result.m[10] = c;
  2089. result.m[9] = -s;
  2090. result.m[6] = s;
  2091. result.m[1] = 0;
  2092. result.m[2] = 0;
  2093. result.m[3] = 0;
  2094. result.m[4] = 0;
  2095. result.m[7] = 0;
  2096. result.m[8] = 0;
  2097. result.m[11] = 0;
  2098. result.m[12] = 0;
  2099. result.m[13] = 0;
  2100. result.m[14] = 0;
  2101. };
  2102. Matrix.RotationY = function (angle) {
  2103. var result = new Matrix();
  2104. Matrix.RotationYToRef(angle, result);
  2105. return result;
  2106. };
  2107. Matrix.RotationYToRef = function (angle, result) {
  2108. var s = Math.sin(angle);
  2109. var c = Math.cos(angle);
  2110. result.m[5] = 1.0;
  2111. result.m[15] = 1.0;
  2112. result.m[0] = c;
  2113. result.m[2] = -s;
  2114. result.m[8] = s;
  2115. result.m[10] = c;
  2116. result.m[1] = 0;
  2117. result.m[3] = 0;
  2118. result.m[4] = 0;
  2119. result.m[6] = 0;
  2120. result.m[7] = 0;
  2121. result.m[9] = 0;
  2122. result.m[11] = 0;
  2123. result.m[12] = 0;
  2124. result.m[13] = 0;
  2125. result.m[14] = 0;
  2126. };
  2127. Matrix.RotationZ = function (angle) {
  2128. var result = new Matrix();
  2129. Matrix.RotationZToRef(angle, result);
  2130. return result;
  2131. };
  2132. Matrix.RotationZToRef = function (angle, result) {
  2133. var s = Math.sin(angle);
  2134. var c = Math.cos(angle);
  2135. result.m[10] = 1.0;
  2136. result.m[15] = 1.0;
  2137. result.m[0] = c;
  2138. result.m[1] = s;
  2139. result.m[4] = -s;
  2140. result.m[5] = c;
  2141. result.m[2] = 0;
  2142. result.m[3] = 0;
  2143. result.m[6] = 0;
  2144. result.m[7] = 0;
  2145. result.m[8] = 0;
  2146. result.m[9] = 0;
  2147. result.m[11] = 0;
  2148. result.m[12] = 0;
  2149. result.m[13] = 0;
  2150. result.m[14] = 0;
  2151. };
  2152. Matrix.RotationAxis = function (axis, angle) {
  2153. var result = Matrix.Zero();
  2154. Matrix.RotationAxisToRef(axis, angle, result);
  2155. return result;
  2156. };
  2157. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2158. var s = Math.sin(-angle);
  2159. var c = Math.cos(-angle);
  2160. var c1 = 1 - c;
  2161. axis.normalize();
  2162. result.m[0] = (axis.x * axis.x) * c1 + c;
  2163. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2164. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2165. result.m[3] = 0.0;
  2166. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2167. result.m[5] = (axis.y * axis.y) * c1 + c;
  2168. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2169. result.m[7] = 0.0;
  2170. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2171. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2172. result.m[10] = (axis.z * axis.z) * c1 + c;
  2173. result.m[11] = 0.0;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2177. var result = new Matrix();
  2178. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2179. return result;
  2180. };
  2181. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2183. this._tempQuaternion.toRotationMatrix(result);
  2184. };
  2185. Matrix.Scaling = function (x, y, z) {
  2186. var result = Matrix.Zero();
  2187. Matrix.ScalingToRef(x, y, z, result);
  2188. return result;
  2189. };
  2190. Matrix.ScalingToRef = function (x, y, z, result) {
  2191. result.m[0] = x;
  2192. result.m[1] = 0;
  2193. result.m[2] = 0;
  2194. result.m[3] = 0;
  2195. result.m[4] = 0;
  2196. result.m[5] = y;
  2197. result.m[6] = 0;
  2198. result.m[7] = 0;
  2199. result.m[8] = 0;
  2200. result.m[9] = 0;
  2201. result.m[10] = z;
  2202. result.m[11] = 0;
  2203. result.m[12] = 0;
  2204. result.m[13] = 0;
  2205. result.m[14] = 0;
  2206. result.m[15] = 1.0;
  2207. };
  2208. Matrix.Translation = function (x, y, z) {
  2209. var result = Matrix.Identity();
  2210. Matrix.TranslationToRef(x, y, z, result);
  2211. return result;
  2212. };
  2213. Matrix.TranslationToRef = function (x, y, z, result) {
  2214. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2215. };
  2216. Matrix.Lerp = function (startValue, endValue, gradient) {
  2217. var result = Matrix.Zero();
  2218. for (var index = 0; index < 16; index++) {
  2219. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2220. }
  2221. return result;
  2222. };
  2223. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2224. var startScale = new Vector3(0, 0, 0);
  2225. var startRotation = new Quaternion();
  2226. var startTranslation = new Vector3(0, 0, 0);
  2227. startValue.decompose(startScale, startRotation, startTranslation);
  2228. var endScale = new Vector3(0, 0, 0);
  2229. var endRotation = new Quaternion();
  2230. var endTranslation = new Vector3(0, 0, 0);
  2231. endValue.decompose(endScale, endRotation, endTranslation);
  2232. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2233. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2234. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2235. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2236. };
  2237. Matrix.LookAtLH = function (eye, target, up) {
  2238. var result = Matrix.Zero();
  2239. Matrix.LookAtLHToRef(eye, target, up, result);
  2240. return result;
  2241. };
  2242. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2243. // Z axis
  2244. target.subtractToRef(eye, this._zAxis);
  2245. this._zAxis.normalize();
  2246. // X axis
  2247. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2248. if (this._xAxis.lengthSquared() === 0) {
  2249. this._xAxis.x = 1.0;
  2250. }
  2251. else {
  2252. this._xAxis.normalize();
  2253. }
  2254. // Y axis
  2255. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2256. this._yAxis.normalize();
  2257. // Eye angles
  2258. var ex = -Vector3.Dot(this._xAxis, eye);
  2259. var ey = -Vector3.Dot(this._yAxis, eye);
  2260. var ez = -Vector3.Dot(this._zAxis, eye);
  2261. 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);
  2262. };
  2263. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2264. var matrix = Matrix.Zero();
  2265. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2266. return matrix;
  2267. };
  2268. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2269. var hw = 2.0 / width;
  2270. var hh = 2.0 / height;
  2271. var id = 1.0 / (zfar - znear);
  2272. var nid = znear / (znear - zfar);
  2273. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2274. };
  2275. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2276. var matrix = Matrix.Zero();
  2277. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2278. return matrix;
  2279. };
  2280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2281. result.m[0] = 2.0 / (right - left);
  2282. result.m[1] = result.m[2] = result.m[3] = 0;
  2283. result.m[5] = 2.0 / (top - bottom);
  2284. result.m[4] = result.m[6] = result.m[7] = 0;
  2285. result.m[10] = -1.0 / (znear - zfar);
  2286. result.m[8] = result.m[9] = result.m[11] = 0;
  2287. result.m[12] = (left + right) / (left - right);
  2288. result.m[13] = (top + bottom) / (bottom - top);
  2289. result.m[14] = znear / (znear - zfar);
  2290. result.m[15] = 1.0;
  2291. };
  2292. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2293. var matrix = Matrix.Zero();
  2294. matrix.m[0] = (2.0 * znear) / width;
  2295. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2296. matrix.m[5] = (2.0 * znear) / height;
  2297. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2298. matrix.m[10] = -zfar / (znear - zfar);
  2299. matrix.m[8] = matrix.m[9] = 0.0;
  2300. matrix.m[11] = 1.0;
  2301. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2302. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2303. return matrix;
  2304. };
  2305. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2306. var matrix = Matrix.Zero();
  2307. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2308. return matrix;
  2309. };
  2310. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2311. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2312. var tan = 1.0 / (Math.tan(fov * 0.5));
  2313. if (isVerticalFovFixed) {
  2314. result.m[0] = tan / aspect;
  2315. }
  2316. else {
  2317. result.m[0] = tan;
  2318. }
  2319. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2320. if (isVerticalFovFixed) {
  2321. result.m[5] = tan;
  2322. }
  2323. else {
  2324. result.m[5] = tan * aspect;
  2325. }
  2326. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2327. result.m[8] = result.m[9] = 0.0;
  2328. result.m[10] = -zfar / (znear - zfar);
  2329. result.m[11] = 1.0;
  2330. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2331. result.m[14] = (znear * zfar) / (znear - zfar);
  2332. };
  2333. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2334. var cw = viewport.width;
  2335. var ch = viewport.height;
  2336. var cx = viewport.x;
  2337. var cy = viewport.y;
  2338. 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);
  2339. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2340. };
  2341. Matrix.GetAsMatrix2x2 = function (matrix) {
  2342. return new Float32Array([
  2343. matrix.m[0], matrix.m[1],
  2344. matrix.m[4], matrix.m[5]
  2345. ]);
  2346. };
  2347. Matrix.GetAsMatrix3x3 = function (matrix) {
  2348. return new Float32Array([
  2349. matrix.m[0], matrix.m[1], matrix.m[2],
  2350. matrix.m[4], matrix.m[5], matrix.m[6],
  2351. matrix.m[8], matrix.m[9], matrix.m[10]
  2352. ]);
  2353. };
  2354. Matrix.Transpose = function (matrix) {
  2355. var result = new Matrix();
  2356. result.m[0] = matrix.m[0];
  2357. result.m[1] = matrix.m[4];
  2358. result.m[2] = matrix.m[8];
  2359. result.m[3] = matrix.m[12];
  2360. result.m[4] = matrix.m[1];
  2361. result.m[5] = matrix.m[5];
  2362. result.m[6] = matrix.m[9];
  2363. result.m[7] = matrix.m[13];
  2364. result.m[8] = matrix.m[2];
  2365. result.m[9] = matrix.m[6];
  2366. result.m[10] = matrix.m[10];
  2367. result.m[11] = matrix.m[14];
  2368. result.m[12] = matrix.m[3];
  2369. result.m[13] = matrix.m[7];
  2370. result.m[14] = matrix.m[11];
  2371. result.m[15] = matrix.m[15];
  2372. return result;
  2373. };
  2374. Matrix.Reflection = function (plane) {
  2375. var matrix = new Matrix();
  2376. Matrix.ReflectionToRef(plane, matrix);
  2377. return matrix;
  2378. };
  2379. Matrix.ReflectionToRef = function (plane, result) {
  2380. plane.normalize();
  2381. var x = plane.normal.x;
  2382. var y = plane.normal.y;
  2383. var z = plane.normal.z;
  2384. var temp = -2 * x;
  2385. var temp2 = -2 * y;
  2386. var temp3 = -2 * z;
  2387. result.m[0] = (temp * x) + 1;
  2388. result.m[1] = temp2 * x;
  2389. result.m[2] = temp3 * x;
  2390. result.m[3] = 0.0;
  2391. result.m[4] = temp * y;
  2392. result.m[5] = (temp2 * y) + 1;
  2393. result.m[6] = temp3 * y;
  2394. result.m[7] = 0.0;
  2395. result.m[8] = temp * z;
  2396. result.m[9] = temp2 * z;
  2397. result.m[10] = (temp3 * z) + 1;
  2398. result.m[11] = 0.0;
  2399. result.m[12] = temp * plane.d;
  2400. result.m[13] = temp2 * plane.d;
  2401. result.m[14] = temp3 * plane.d;
  2402. result.m[15] = 1.0;
  2403. };
  2404. Matrix._tempQuaternion = new Quaternion();
  2405. Matrix._xAxis = Vector3.Zero();
  2406. Matrix._yAxis = Vector3.Zero();
  2407. Matrix._zAxis = Vector3.Zero();
  2408. return Matrix;
  2409. })();
  2410. BABYLON.Matrix = Matrix;
  2411. var Plane = (function () {
  2412. function Plane(a, b, c, d) {
  2413. this.normal = new Vector3(a, b, c);
  2414. this.d = d;
  2415. }
  2416. Plane.prototype.asArray = function () {
  2417. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2418. };
  2419. // Methods
  2420. Plane.prototype.clone = function () {
  2421. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2422. };
  2423. Plane.prototype.getClassName = function () {
  2424. return "Plane";
  2425. };
  2426. Plane.prototype.getHashCode = function () {
  2427. var hash = this.normal.getHashCode();
  2428. hash = (hash * 397) ^ (this.d || 0);
  2429. return hash;
  2430. };
  2431. Plane.prototype.normalize = function () {
  2432. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2433. var magnitude = 0;
  2434. if (norm !== 0) {
  2435. magnitude = 1.0 / norm;
  2436. }
  2437. this.normal.x *= magnitude;
  2438. this.normal.y *= magnitude;
  2439. this.normal.z *= magnitude;
  2440. this.d *= magnitude;
  2441. return this;
  2442. };
  2443. Plane.prototype.transform = function (transformation) {
  2444. var transposedMatrix = Matrix.Transpose(transformation);
  2445. var x = this.normal.x;
  2446. var y = this.normal.y;
  2447. var z = this.normal.z;
  2448. var d = this.d;
  2449. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2450. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2451. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2452. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2453. return new Plane(normalX, normalY, normalZ, finalD);
  2454. };
  2455. Plane.prototype.dotCoordinate = function (point) {
  2456. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2457. };
  2458. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2459. var x1 = point2.x - point1.x;
  2460. var y1 = point2.y - point1.y;
  2461. var z1 = point2.z - point1.z;
  2462. var x2 = point3.x - point1.x;
  2463. var y2 = point3.y - point1.y;
  2464. var z2 = point3.z - point1.z;
  2465. var yz = (y1 * z2) - (z1 * y2);
  2466. var xz = (z1 * x2) - (x1 * z2);
  2467. var xy = (x1 * y2) - (y1 * x2);
  2468. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2469. var invPyth;
  2470. if (pyth !== 0) {
  2471. invPyth = 1.0 / pyth;
  2472. }
  2473. else {
  2474. invPyth = 0;
  2475. }
  2476. this.normal.x = yz * invPyth;
  2477. this.normal.y = xz * invPyth;
  2478. this.normal.z = xy * invPyth;
  2479. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2480. return this;
  2481. };
  2482. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2483. var dot = Vector3.Dot(this.normal, direction);
  2484. return (dot <= epsilon);
  2485. };
  2486. Plane.prototype.signedDistanceTo = function (point) {
  2487. return Vector3.Dot(point, this.normal) + this.d;
  2488. };
  2489. // Statics
  2490. Plane.FromArray = function (array) {
  2491. return new Plane(array[0], array[1], array[2], array[3]);
  2492. };
  2493. Plane.FromPoints = function (point1, point2, point3) {
  2494. var result = new Plane(0, 0, 0, 0);
  2495. result.copyFromPoints(point1, point2, point3);
  2496. return result;
  2497. };
  2498. Plane.FromPositionAndNormal = function (origin, normal) {
  2499. var result = new Plane(0, 0, 0, 0);
  2500. normal.normalize();
  2501. result.normal = normal;
  2502. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2503. return result;
  2504. };
  2505. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2506. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2507. return Vector3.Dot(point, normal) + d;
  2508. };
  2509. return Plane;
  2510. })();
  2511. BABYLON.Plane = Plane;
  2512. var Viewport = (function () {
  2513. function Viewport(x, y, width, height) {
  2514. this.x = x;
  2515. this.y = y;
  2516. this.width = width;
  2517. this.height = height;
  2518. }
  2519. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2520. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2521. };
  2522. return Viewport;
  2523. })();
  2524. BABYLON.Viewport = Viewport;
  2525. var Frustum = (function () {
  2526. function Frustum() {
  2527. }
  2528. Frustum.GetPlanes = function (transform) {
  2529. var frustumPlanes = [];
  2530. for (var index = 0; index < 6; index++) {
  2531. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2532. }
  2533. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2534. return frustumPlanes;
  2535. };
  2536. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2537. // Near
  2538. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2539. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2540. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2541. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2542. frustumPlanes[0].normalize();
  2543. // Far
  2544. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2545. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2546. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2547. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2548. frustumPlanes[1].normalize();
  2549. // Left
  2550. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2551. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2552. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2553. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2554. frustumPlanes[2].normalize();
  2555. // Right
  2556. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2557. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2558. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2559. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2560. frustumPlanes[3].normalize();
  2561. // Top
  2562. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2563. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2564. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2565. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2566. frustumPlanes[4].normalize();
  2567. // Bottom
  2568. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2569. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2570. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2571. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2572. frustumPlanes[5].normalize();
  2573. };
  2574. return Frustum;
  2575. })();
  2576. BABYLON.Frustum = Frustum;
  2577. (function (Space) {
  2578. Space[Space["LOCAL"] = 0] = "LOCAL";
  2579. Space[Space["WORLD"] = 1] = "WORLD";
  2580. })(BABYLON.Space || (BABYLON.Space = {}));
  2581. var Space = BABYLON.Space;
  2582. var Axis = (function () {
  2583. function Axis() {
  2584. }
  2585. Axis.X = new Vector3(1, 0, 0);
  2586. Axis.Y = new Vector3(0, 1, 0);
  2587. Axis.Z = new Vector3(0, 0, 1);
  2588. return Axis;
  2589. })();
  2590. BABYLON.Axis = Axis;
  2591. ;
  2592. var BezierCurve = (function () {
  2593. function BezierCurve() {
  2594. }
  2595. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2596. // Extract X (which is equal to time here)
  2597. var f0 = 1 - 3 * x2 + 3 * x1;
  2598. var f1 = 3 * x2 - 6 * x1;
  2599. var f2 = 3 * x1;
  2600. var refinedT = t;
  2601. for (var i = 0; i < 5; i++) {
  2602. var refinedT2 = refinedT * refinedT;
  2603. var refinedT3 = refinedT2 * refinedT;
  2604. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2605. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2606. refinedT -= (x - t) * slope;
  2607. refinedT = Math.min(1, Math.max(0, refinedT));
  2608. }
  2609. // Resolve cubic bezier for the given x
  2610. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2611. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2612. Math.pow(refinedT, 3);
  2613. };
  2614. return BezierCurve;
  2615. })();
  2616. BABYLON.BezierCurve = BezierCurve;
  2617. (function (Orientation) {
  2618. Orientation[Orientation["CW"] = 0] = "CW";
  2619. Orientation[Orientation["CCW"] = 1] = "CCW";
  2620. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2621. var Orientation = BABYLON.Orientation;
  2622. var Angle = (function () {
  2623. function Angle(radians) {
  2624. var _this = this;
  2625. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2626. this.radians = function () { return _this._radians; };
  2627. this._radians = radians;
  2628. if (this._radians < 0)
  2629. this._radians += (2 * Math.PI);
  2630. }
  2631. Angle.BetweenTwoPoints = function (a, b) {
  2632. var delta = b.subtract(a);
  2633. var theta = Math.atan2(delta.y, delta.x);
  2634. return new Angle(theta);
  2635. };
  2636. Angle.FromRadians = function (radians) {
  2637. return new Angle(radians);
  2638. };
  2639. Angle.FromDegrees = function (degrees) {
  2640. return new Angle(degrees * Math.PI / 180);
  2641. };
  2642. return Angle;
  2643. })();
  2644. BABYLON.Angle = Angle;
  2645. var Arc2 = (function () {
  2646. function Arc2(startPoint, midPoint, endPoint) {
  2647. this.startPoint = startPoint;
  2648. this.midPoint = midPoint;
  2649. this.endPoint = endPoint;
  2650. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2651. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2652. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2653. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2654. 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);
  2655. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2656. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2657. var a1 = this.startAngle.degrees();
  2658. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2659. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2660. // angles correction
  2661. if (a2 - a1 > +180.0)
  2662. a2 -= 360.0;
  2663. if (a2 - a1 < -180.0)
  2664. a2 += 360.0;
  2665. if (a3 - a2 > +180.0)
  2666. a3 -= 360.0;
  2667. if (a3 - a2 < -180.0)
  2668. a3 += 360.0;
  2669. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2670. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2671. }
  2672. return Arc2;
  2673. })();
  2674. BABYLON.Arc2 = Arc2;
  2675. var Path2 = (function () {
  2676. function Path2(x, y) {
  2677. this._points = new Array();
  2678. this._length = 0;
  2679. this.closed = false;
  2680. this._points.push(new Vector2(x, y));
  2681. }
  2682. Path2.prototype.addLineTo = function (x, y) {
  2683. if (closed) {
  2684. //Tools.Error("cannot add lines to closed paths");
  2685. return this;
  2686. }
  2687. var newPoint = new Vector2(x, y);
  2688. var previousPoint = this._points[this._points.length - 1];
  2689. this._points.push(newPoint);
  2690. this._length += newPoint.subtract(previousPoint).length();
  2691. return this;
  2692. };
  2693. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2694. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2695. if (closed) {
  2696. //Tools.Error("cannot add arcs to closed paths");
  2697. return this;
  2698. }
  2699. var startPoint = this._points[this._points.length - 1];
  2700. var midPoint = new Vector2(midX, midY);
  2701. var endPoint = new Vector2(endX, endY);
  2702. var arc = new Arc2(startPoint, midPoint, endPoint);
  2703. var increment = arc.angle.radians() / numberOfSegments;
  2704. if (arc.orientation === Orientation.CW)
  2705. increment *= -1;
  2706. var currentAngle = arc.startAngle.radians() + increment;
  2707. for (var i = 0; i < numberOfSegments; i++) {
  2708. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2709. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2710. this.addLineTo(x, y);
  2711. currentAngle += increment;
  2712. }
  2713. return this;
  2714. };
  2715. Path2.prototype.close = function () {
  2716. this.closed = true;
  2717. return this;
  2718. };
  2719. Path2.prototype.length = function () {
  2720. var result = this._length;
  2721. if (!this.closed) {
  2722. var lastPoint = this._points[this._points.length - 1];
  2723. var firstPoint = this._points[0];
  2724. result += (firstPoint.subtract(lastPoint).length());
  2725. }
  2726. return result;
  2727. };
  2728. Path2.prototype.getPoints = function () {
  2729. return this._points;
  2730. };
  2731. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2732. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2733. //Tools.Error("normalized length position should be between 0 and 1.");
  2734. return Vector2.Zero();
  2735. }
  2736. var lengthPosition = normalizedLengthPosition * this.length();
  2737. var previousOffset = 0;
  2738. for (var i = 0; i < this._points.length; i++) {
  2739. var j = (i + 1) % this._points.length;
  2740. var a = this._points[i];
  2741. var b = this._points[j];
  2742. var bToA = b.subtract(a);
  2743. var nextOffset = (bToA.length() + previousOffset);
  2744. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2745. var dir = bToA.normalize();
  2746. var localOffset = lengthPosition - previousOffset;
  2747. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2748. }
  2749. previousOffset = nextOffset;
  2750. }
  2751. //Tools.Error("internal error");
  2752. return Vector2.Zero();
  2753. };
  2754. Path2.StartingAt = function (x, y) {
  2755. return new Path2(x, y);
  2756. };
  2757. return Path2;
  2758. })();
  2759. BABYLON.Path2 = Path2;
  2760. var Path3D = (function () {
  2761. /**
  2762. * new Path3D(path, normal, raw)
  2763. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2764. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2765. * path : an array of Vector3, the curve axis of the Path3D
  2766. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2767. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2768. */
  2769. function Path3D(path, firstNormal, raw) {
  2770. this.path = path;
  2771. this._curve = new Array();
  2772. this._distances = new Array();
  2773. this._tangents = new Array();
  2774. this._normals = new Array();
  2775. this._binormals = new Array();
  2776. for (var p = 0; p < path.length; p++) {
  2777. this._curve[p] = path[p].clone(); // hard copy
  2778. }
  2779. this._raw = raw || false;
  2780. this._compute(firstNormal);
  2781. }
  2782. /**
  2783. * Returns the Path3D array of successive Vector3 designing its curve.
  2784. */
  2785. Path3D.prototype.getCurve = function () {
  2786. return this._curve;
  2787. };
  2788. /**
  2789. * Returns an array populated with tangent vectors on each Path3D curve point.
  2790. */
  2791. Path3D.prototype.getTangents = function () {
  2792. return this._tangents;
  2793. };
  2794. /**
  2795. * Returns an array populated with normal vectors on each Path3D curve point.
  2796. */
  2797. Path3D.prototype.getNormals = function () {
  2798. return this._normals;
  2799. };
  2800. /**
  2801. * Returns an array populated with binormal vectors on each Path3D curve point.
  2802. */
  2803. Path3D.prototype.getBinormals = function () {
  2804. return this._binormals;
  2805. };
  2806. /**
  2807. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2808. */
  2809. Path3D.prototype.getDistances = function () {
  2810. return this._distances;
  2811. };
  2812. /**
  2813. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2814. * Returns the same object updated.
  2815. */
  2816. Path3D.prototype.update = function (path, firstNormal) {
  2817. for (var p = 0; p < path.length; p++) {
  2818. this._curve[p].x = path[p].x;
  2819. this._curve[p].y = path[p].y;
  2820. this._curve[p].z = path[p].z;
  2821. }
  2822. this._compute(firstNormal);
  2823. return this;
  2824. };
  2825. // private function compute() : computes tangents, normals and binormals
  2826. Path3D.prototype._compute = function (firstNormal) {
  2827. var l = this._curve.length;
  2828. // first and last tangents
  2829. this._tangents[0] = this._getFirstNonNullVector(0);
  2830. if (!this._raw) {
  2831. this._tangents[0].normalize();
  2832. }
  2833. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2834. if (!this._raw) {
  2835. this._tangents[l - 1].normalize();
  2836. }
  2837. // normals and binormals at first point : arbitrary vector with _normalVector()
  2838. var tg0 = this._tangents[0];
  2839. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2840. this._normals[0] = pp0;
  2841. if (!this._raw) {
  2842. this._normals[0].normalize();
  2843. }
  2844. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2845. if (!this._raw) {
  2846. this._binormals[0].normalize();
  2847. }
  2848. this._distances[0] = 0;
  2849. // normals and binormals : next points
  2850. var prev; // previous vector (segment)
  2851. var cur; // current vector (segment)
  2852. var curTang; // current tangent
  2853. // previous normal
  2854. var prevBinor; // previous binormal
  2855. for (var i = 1; i < l; i++) {
  2856. // tangents
  2857. prev = this._getLastNonNullVector(i);
  2858. if (i < l - 1) {
  2859. cur = this._getFirstNonNullVector(i);
  2860. this._tangents[i] = prev.add(cur);
  2861. this._tangents[i].normalize();
  2862. }
  2863. this._distances[i] = this._distances[i - 1] + prev.length();
  2864. // normals and binormals
  2865. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2866. curTang = this._tangents[i];
  2867. prevBinor = this._binormals[i - 1];
  2868. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2869. if (!this._raw) {
  2870. this._normals[i].normalize();
  2871. }
  2872. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2873. if (!this._raw) {
  2874. this._binormals[i].normalize();
  2875. }
  2876. }
  2877. };
  2878. // private function getFirstNonNullVector(index)
  2879. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2880. Path3D.prototype._getFirstNonNullVector = function (index) {
  2881. var i = 1;
  2882. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2883. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2884. i++;
  2885. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2886. }
  2887. return nNVector;
  2888. };
  2889. // private function getLastNonNullVector(index)
  2890. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2891. Path3D.prototype._getLastNonNullVector = function (index) {
  2892. var i = 1;
  2893. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2894. while (nLVector.length() === 0 && index > i + 1) {
  2895. i++;
  2896. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2897. }
  2898. return nLVector;
  2899. };
  2900. // private function normalVector(v0, vt, va) :
  2901. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2902. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2903. Path3D.prototype._normalVector = function (v0, vt, va) {
  2904. var normal0;
  2905. if (va === undefined || va === null) {
  2906. var point;
  2907. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2908. point = new Vector3(0, -1, 0);
  2909. }
  2910. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2911. point = new Vector3(1, 0, 0);
  2912. }
  2913. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2914. point = new Vector3(0, 0, 1);
  2915. }
  2916. normal0 = Vector3.Cross(vt, point);
  2917. }
  2918. else {
  2919. normal0 = Vector3.Cross(vt, va);
  2920. Vector3.CrossToRef(normal0, vt, normal0);
  2921. }
  2922. normal0.normalize();
  2923. return normal0;
  2924. };
  2925. return Path3D;
  2926. })();
  2927. BABYLON.Path3D = Path3D;
  2928. var Curve3 = (function () {
  2929. /**
  2930. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2931. * A Curve3 is designed from a series of successive Vector3.
  2932. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2933. */
  2934. function Curve3(points) {
  2935. this._length = 0;
  2936. this._points = points;
  2937. this._length = this._computeLength(points);
  2938. }
  2939. /**
  2940. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2941. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2942. * @param v1 (Vector3) the control point
  2943. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2944. * @param nbPoints (integer) the wanted number of points in the curve
  2945. */
  2946. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2947. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2948. var bez = new Array();
  2949. var equation = function (t, val0, val1, val2) {
  2950. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2951. return res;
  2952. };
  2953. for (var i = 0; i <= nbPoints; i++) {
  2954. 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)));
  2955. }
  2956. return new Curve3(bez);
  2957. };
  2958. /**
  2959. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2960. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2961. * @param v1 (Vector3) the first control point
  2962. * @param v2 (Vector3) the second control point
  2963. * @param v3 (Vector3) the end point of the Cubic Bezier
  2964. * @param nbPoints (integer) the wanted number of points in the curve
  2965. */
  2966. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2967. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2968. var bez = new Array();
  2969. var equation = function (t, val0, val1, val2, val3) {
  2970. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2971. return res;
  2972. };
  2973. for (var i = 0; i <= nbPoints; i++) {
  2974. 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)));
  2975. }
  2976. return new Curve3(bez);
  2977. };
  2978. /**
  2979. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2980. * @param p1 (Vector3) the origin point of the Hermite Spline
  2981. * @param t1 (Vector3) the tangent vector at the origin point
  2982. * @param p2 (Vector3) the end point of the Hermite Spline
  2983. * @param t2 (Vector3) the tangent vector at the end point
  2984. * @param nbPoints (integer) the wanted number of points in the curve
  2985. */
  2986. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2987. var hermite = new Array();
  2988. var step = 1 / nbPoints;
  2989. for (var i = 0; i <= nbPoints; i++) {
  2990. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2991. }
  2992. return new Curve3(hermite);
  2993. };
  2994. /**
  2995. * Returns the Curve3 stored array of successive Vector3
  2996. */
  2997. Curve3.prototype.getPoints = function () {
  2998. return this._points;
  2999. };
  3000. /**
  3001. * Returns the computed length (float) of the curve.
  3002. */
  3003. Curve3.prototype.length = function () {
  3004. return this._length;
  3005. };
  3006. /**
  3007. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3008. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3009. * curveA and curveB keep unchanged.
  3010. */
  3011. Curve3.prototype.continue = function (curve) {
  3012. var lastPoint = this._points[this._points.length - 1];
  3013. var continuedPoints = this._points.slice();
  3014. var curvePoints = curve.getPoints();
  3015. for (var i = 1; i < curvePoints.length; i++) {
  3016. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3017. }
  3018. var continuedCurve = new Curve3(continuedPoints);
  3019. return continuedCurve;
  3020. };
  3021. Curve3.prototype._computeLength = function (path) {
  3022. var l = 0;
  3023. for (var i = 1; i < path.length; i++) {
  3024. l += (path[i].subtract(path[i - 1])).length();
  3025. }
  3026. return l;
  3027. };
  3028. return Curve3;
  3029. })();
  3030. BABYLON.Curve3 = Curve3;
  3031. // SphericalHarmonics
  3032. var SphericalHarmonics = (function () {
  3033. function SphericalHarmonics() {
  3034. this.L00 = Vector3.Zero();
  3035. this.L1_1 = Vector3.Zero();
  3036. this.L10 = Vector3.Zero();
  3037. this.L11 = Vector3.Zero();
  3038. this.L2_2 = Vector3.Zero();
  3039. this.L2_1 = Vector3.Zero();
  3040. this.L20 = Vector3.Zero();
  3041. this.L21 = Vector3.Zero();
  3042. this.L22 = Vector3.Zero();
  3043. }
  3044. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3045. var colorVector = new Vector3(color.r, color.g, color.b);
  3046. var c = colorVector.scale(deltaSolidAngle);
  3047. this.L00 = this.L00.add(c.scale(0.282095));
  3048. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3049. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3050. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3051. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3052. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3053. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3054. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3055. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3056. };
  3057. SphericalHarmonics.prototype.scale = function (scale) {
  3058. this.L00 = this.L00.scale(scale);
  3059. this.L1_1 = this.L1_1.scale(scale);
  3060. this.L10 = this.L10.scale(scale);
  3061. this.L11 = this.L11.scale(scale);
  3062. this.L2_2 = this.L2_2.scale(scale);
  3063. this.L2_1 = this.L2_1.scale(scale);
  3064. this.L20 = this.L20.scale(scale);
  3065. this.L21 = this.L21.scale(scale);
  3066. this.L22 = this.L22.scale(scale);
  3067. };
  3068. return SphericalHarmonics;
  3069. })();
  3070. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3071. // SphericalPolynomial
  3072. var SphericalPolynomial = (function () {
  3073. function SphericalPolynomial() {
  3074. this.x = Vector3.Zero();
  3075. this.y = Vector3.Zero();
  3076. this.z = Vector3.Zero();
  3077. this.xx = Vector3.Zero();
  3078. this.yy = Vector3.Zero();
  3079. this.zz = Vector3.Zero();
  3080. this.xy = Vector3.Zero();
  3081. this.yz = Vector3.Zero();
  3082. this.zx = Vector3.Zero();
  3083. }
  3084. SphericalPolynomial.prototype.addAmbient = function (color) {
  3085. var colorVector = new Vector3(color.r, color.g, color.b);
  3086. this.xx = this.xx.add(colorVector);
  3087. this.yy = this.yy.add(colorVector);
  3088. this.zz = this.zz.add(colorVector);
  3089. };
  3090. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3091. var result = new SphericalPolynomial();
  3092. result.x = harmonics.L11.scale(1.02333);
  3093. result.y = harmonics.L1_1.scale(1.02333);
  3094. result.z = harmonics.L10.scale(1.02333);
  3095. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3096. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3097. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3098. result.yz = harmonics.L2_1.scale(0.858086);
  3099. result.zx = harmonics.L21.scale(0.858086);
  3100. result.xy = harmonics.L2_2.scale(0.858086);
  3101. return result;
  3102. };
  3103. return SphericalPolynomial;
  3104. })();
  3105. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3106. // Vertex formats
  3107. var PositionNormalVertex = (function () {
  3108. function PositionNormalVertex(position, normal) {
  3109. if (position === void 0) { position = Vector3.Zero(); }
  3110. if (normal === void 0) { normal = Vector3.Up(); }
  3111. this.position = position;
  3112. this.normal = normal;
  3113. }
  3114. PositionNormalVertex.prototype.clone = function () {
  3115. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3116. };
  3117. return PositionNormalVertex;
  3118. })();
  3119. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3120. var PositionNormalTextureVertex = (function () {
  3121. function PositionNormalTextureVertex(position, normal, uv) {
  3122. if (position === void 0) { position = Vector3.Zero(); }
  3123. if (normal === void 0) { normal = Vector3.Up(); }
  3124. if (uv === void 0) { uv = Vector2.Zero(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. this.uv = uv;
  3128. }
  3129. PositionNormalTextureVertex.prototype.clone = function () {
  3130. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3131. };
  3132. return PositionNormalTextureVertex;
  3133. })();
  3134. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3135. // Temporary pre-allocated objects for engine internal use
  3136. // usage in any internal function :
  3137. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3138. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3139. var Tmp = (function () {
  3140. function Tmp() {
  3141. }
  3142. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3143. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3144. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3145. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3146. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3147. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3148. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3149. Matrix.Zero(), Matrix.Zero(),
  3150. Matrix.Zero(), Matrix.Zero(),
  3151. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3152. return Tmp;
  3153. })();
  3154. BABYLON.Tmp = Tmp;
  3155. })(BABYLON || (BABYLON = {}));
  3156. var BABYLON;
  3157. (function (BABYLON) {
  3158. function generateSerializableMember(type, sourceName) {
  3159. return function (target, propertyKey) {
  3160. if (!target.__serializableMembers) {
  3161. target.__serializableMembers = {};
  3162. }
  3163. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3164. };
  3165. }
  3166. function serialize(sourceName) {
  3167. return generateSerializableMember(0, sourceName); // value member
  3168. }
  3169. BABYLON.serialize = serialize;
  3170. function serializeAsTexture(sourceName) {
  3171. return generateSerializableMember(1, sourceName); // texture member
  3172. }
  3173. BABYLON.serializeAsTexture = serializeAsTexture;
  3174. function serializeAsColor3(sourceName) {
  3175. return generateSerializableMember(2, sourceName); // color3 member
  3176. }
  3177. BABYLON.serializeAsColor3 = serializeAsColor3;
  3178. function serializeAsFresnelParameters(sourceName) {
  3179. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3180. }
  3181. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3182. function serializeAsVector2(sourceName) {
  3183. return generateSerializableMember(4, sourceName); // vector2 member
  3184. }
  3185. BABYLON.serializeAsVector2 = serializeAsVector2;
  3186. function serializeAsVector3(sourceName) {
  3187. return generateSerializableMember(5, sourceName); // vector3 member
  3188. }
  3189. BABYLON.serializeAsVector3 = serializeAsVector3;
  3190. function serializeAsMeshReference(sourceName) {
  3191. return generateSerializableMember(6, sourceName); // mesh reference member
  3192. }
  3193. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3194. function serializeAsColorCurves(sourceName) {
  3195. return generateSerializableMember(7, sourceName); // color curves
  3196. }
  3197. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3198. var SerializationHelper = (function () {
  3199. function SerializationHelper() {
  3200. }
  3201. SerializationHelper.Serialize = function (entity, serializationObject) {
  3202. if (!serializationObject) {
  3203. serializationObject = {};
  3204. }
  3205. // Tags
  3206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3207. // Properties
  3208. for (var property in entity.__serializableMembers) {
  3209. var propertyDescriptor = entity.__serializableMembers[property];
  3210. var targetPropertyName = propertyDescriptor.sourceName || property;
  3211. var propertyType = propertyDescriptor.type;
  3212. var sourceProperty = entity[property];
  3213. if (sourceProperty !== undefined && sourceProperty !== null) {
  3214. switch (propertyType) {
  3215. case 0:
  3216. serializationObject[targetPropertyName] = sourceProperty;
  3217. break;
  3218. case 1:
  3219. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3220. break;
  3221. case 2:
  3222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3223. break;
  3224. case 3:
  3225. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3226. break;
  3227. case 4:
  3228. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3229. break;
  3230. case 5:
  3231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3232. break;
  3233. case 6:
  3234. serializationObject[targetPropertyName] = sourceProperty.id;
  3235. break;
  3236. case 7:
  3237. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3238. break;
  3239. }
  3240. }
  3241. }
  3242. return serializationObject;
  3243. };
  3244. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3245. var destination = creationFunction();
  3246. // Tags
  3247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3248. // Properties
  3249. for (var property in destination.__serializableMembers) {
  3250. var propertyDescriptor = destination.__serializableMembers[property];
  3251. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3252. var propertyType = propertyDescriptor.type;
  3253. if (sourceProperty !== undefined && sourceProperty !== null) {
  3254. switch (propertyType) {
  3255. case 0:
  3256. destination[property] = sourceProperty;
  3257. break;
  3258. case 1:
  3259. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3260. break;
  3261. case 2:
  3262. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3263. break;
  3264. case 3:
  3265. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3266. break;
  3267. case 4:
  3268. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3269. break;
  3270. case 5:
  3271. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3272. break;
  3273. case 6:
  3274. destination[property] = scene.getLastMeshByID(sourceProperty);
  3275. break;
  3276. case 7:
  3277. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3278. break;
  3279. }
  3280. }
  3281. }
  3282. return destination;
  3283. };
  3284. SerializationHelper.Clone = function (creationFunction, source) {
  3285. var destination = creationFunction();
  3286. // Tags
  3287. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3288. // Properties
  3289. for (var property in destination.__serializableMembers) {
  3290. var propertyDescriptor = destination.__serializableMembers[property];
  3291. var sourceProperty = source[property];
  3292. var propertyType = propertyDescriptor.type;
  3293. if (sourceProperty !== undefined && sourceProperty !== null) {
  3294. switch (propertyType) {
  3295. case 0: // Value
  3296. case 6:
  3297. destination[property] = sourceProperty;
  3298. break;
  3299. case 1: // Texture
  3300. case 2: // Color3
  3301. case 3: // FresnelParameters
  3302. case 4: // Vector2
  3303. case 5: // Vector3
  3304. case 7:
  3305. destination[property] = sourceProperty.clone();
  3306. break;
  3307. }
  3308. }
  3309. }
  3310. return destination;
  3311. };
  3312. return SerializationHelper;
  3313. })();
  3314. BABYLON.SerializationHelper = SerializationHelper;
  3315. })(BABYLON || (BABYLON = {}));
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. /**
  3319. * A class serves as a medium between the observable and its observers
  3320. */
  3321. var EventState = (function () {
  3322. /**
  3323. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3324. */
  3325. function EventState(mask, skipNextObservers) {
  3326. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3327. this.initalize(mask, skipNextObservers);
  3328. }
  3329. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3330. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3331. this.mask = mask;
  3332. this.skipNextObservers = skipNextObservers;
  3333. return this;
  3334. };
  3335. return EventState;
  3336. })();
  3337. BABYLON.EventState = EventState;
  3338. /**
  3339. * Represent an Observer registered to a given Observable object.
  3340. */
  3341. var Observer = (function () {
  3342. function Observer(callback, mask) {
  3343. this.callback = callback;
  3344. this.mask = mask;
  3345. }
  3346. return Observer;
  3347. })();
  3348. BABYLON.Observer = Observer;
  3349. /**
  3350. * The Observable class is a simple implementation of the Observable pattern.
  3351. * 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.
  3352. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3353. * 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).
  3354. * 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.
  3355. */
  3356. var Observable = (function () {
  3357. function Observable() {
  3358. this._observers = new Array();
  3359. }
  3360. /**
  3361. * Create a new Observer with the specified callback
  3362. * @param callback the callback that will be executed for that Observer
  3363. * @param mask the mask used to filter observers
  3364. * @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.
  3365. */
  3366. Observable.prototype.add = function (callback, mask, insertFirst) {
  3367. if (mask === void 0) { mask = -1; }
  3368. if (insertFirst === void 0) { insertFirst = false; }
  3369. if (!callback) {
  3370. return null;
  3371. }
  3372. var observer = new Observer(callback, mask);
  3373. if (insertFirst) {
  3374. this._observers.unshift(observer);
  3375. }
  3376. else {
  3377. this._observers.push(observer);
  3378. }
  3379. return observer;
  3380. };
  3381. /**
  3382. * Remove an Observer from the Observable object
  3383. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3384. */
  3385. Observable.prototype.remove = function (observer) {
  3386. var index = this._observers.indexOf(observer);
  3387. if (index !== -1) {
  3388. this._observers.splice(index, 1);
  3389. return true;
  3390. }
  3391. return false;
  3392. };
  3393. /**
  3394. * Remove a callback from the Observable object
  3395. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3396. */
  3397. Observable.prototype.removeCallback = function (callback) {
  3398. for (var index = 0; index < this._observers.length; index++) {
  3399. if (this._observers[index].callback === callback) {
  3400. this._observers.splice(index, 1);
  3401. return true;
  3402. }
  3403. }
  3404. return false;
  3405. };
  3406. /**
  3407. * Notify all Observers by calling their respective callback with the given data
  3408. * @param eventData
  3409. * @param mask
  3410. */
  3411. Observable.prototype.notifyObservers = function (eventData, mask) {
  3412. if (mask === void 0) { mask = -1; }
  3413. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3414. Observable._pooledEventState = null;
  3415. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3416. var obs = _a[_i];
  3417. if (obs.mask & mask) {
  3418. obs.callback(eventData, state);
  3419. }
  3420. if (state.skipNextObservers) {
  3421. break;
  3422. }
  3423. }
  3424. Observable._pooledEventState = state;
  3425. };
  3426. /**
  3427. * return true is the Observable has at least one Observer registered
  3428. */
  3429. Observable.prototype.hasObservers = function () {
  3430. return this._observers.length > 0;
  3431. };
  3432. /**
  3433. * Clear the list of observers
  3434. */
  3435. Observable.prototype.clear = function () {
  3436. this._observers = new Array();
  3437. };
  3438. /**
  3439. * Clone the current observable
  3440. */
  3441. Observable.prototype.clone = function () {
  3442. var result = new Observable();
  3443. result._observers = this._observers.slice(0);
  3444. return result;
  3445. };
  3446. Observable._pooledEventState = null;
  3447. return Observable;
  3448. })();
  3449. BABYLON.Observable = Observable;
  3450. })(BABYLON || (BABYLON = {}));
  3451. var BABYLON;
  3452. (function (BABYLON) {
  3453. var Database = (function () {
  3454. function Database(urlToScene, callbackManifestChecked) {
  3455. // Handling various flavors of prefixed version of IndexedDB
  3456. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3457. this.callbackManifestChecked = callbackManifestChecked;
  3458. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3459. this.db = null;
  3460. this.enableSceneOffline = false;
  3461. this.enableTexturesOffline = false;
  3462. this.manifestVersionFound = 0;
  3463. this.mustUpdateRessources = false;
  3464. this.hasReachedQuota = false;
  3465. if (!Database.IDBStorageEnabled) {
  3466. this.callbackManifestChecked(true);
  3467. }
  3468. else {
  3469. this.checkManifestFile();
  3470. }
  3471. }
  3472. Database.prototype.checkManifestFile = function () {
  3473. var _this = this;
  3474. function noManifestFile() {
  3475. that.enableSceneOffline = false;
  3476. that.enableTexturesOffline = false;
  3477. that.callbackManifestChecked(false);
  3478. }
  3479. var that = this;
  3480. var timeStampUsed = false;
  3481. var manifestURL = this.currentSceneUrl + ".manifest";
  3482. var xhr = new XMLHttpRequest();
  3483. if (navigator.onLine) {
  3484. // Adding a timestamp to by-pass browsers' cache
  3485. timeStampUsed = true;
  3486. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3487. }
  3488. xhr.open("GET", manifestURL, true);
  3489. xhr.addEventListener("load", function () {
  3490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3491. try {
  3492. var manifestFile = JSON.parse(xhr.response);
  3493. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3494. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3496. _this.manifestVersionFound = manifestFile.version;
  3497. }
  3498. if (_this.callbackManifestChecked) {
  3499. _this.callbackManifestChecked(true);
  3500. }
  3501. }
  3502. catch (ex) {
  3503. noManifestFile();
  3504. }
  3505. }
  3506. else {
  3507. noManifestFile();
  3508. }
  3509. }, false);
  3510. xhr.addEventListener("error", function (event) {
  3511. if (timeStampUsed) {
  3512. timeStampUsed = false;
  3513. // Let's retry without the timeStamp
  3514. // It could fail when coupled with HTML5 Offline API
  3515. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3516. xhr.open("GET", retryManifestURL, true);
  3517. xhr.send();
  3518. }
  3519. else {
  3520. noManifestFile();
  3521. }
  3522. }, false);
  3523. try {
  3524. xhr.send();
  3525. }
  3526. catch (ex) {
  3527. BABYLON.Tools.Error("Error on XHR send request.");
  3528. that.callbackManifestChecked(false);
  3529. }
  3530. };
  3531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3532. var _this = this;
  3533. function handleError() {
  3534. that.isSupported = false;
  3535. if (errorCallback)
  3536. errorCallback();
  3537. }
  3538. var that = this;
  3539. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3540. // Your browser doesn't support IndexedDB
  3541. this.isSupported = false;
  3542. if (errorCallback)
  3543. errorCallback();
  3544. }
  3545. else {
  3546. // If the DB hasn't been opened or created yet
  3547. if (!this.db) {
  3548. this.hasReachedQuota = false;
  3549. this.isSupported = true;
  3550. var request = this.idbFactory.open("babylonjs", 1);
  3551. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3552. request.onerror = function (event) {
  3553. handleError();
  3554. };
  3555. // executes when a version change transaction cannot complete due to other active transactions
  3556. request.onblocked = function (event) {
  3557. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3558. handleError();
  3559. };
  3560. // DB has been opened successfully
  3561. request.onsuccess = function (event) {
  3562. _this.db = request.result;
  3563. successCallback();
  3564. };
  3565. // Initialization of the DB. Creating Scenes & Textures stores
  3566. request.onupgradeneeded = function (event) {
  3567. _this.db = (event.target).result;
  3568. try {
  3569. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3570. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3571. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3572. }
  3573. catch (ex) {
  3574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3575. handleError();
  3576. }
  3577. };
  3578. }
  3579. else {
  3580. if (successCallback)
  3581. successCallback();
  3582. }
  3583. }
  3584. };
  3585. Database.prototype.loadImageFromDB = function (url, image) {
  3586. var _this = this;
  3587. var completeURL = Database.ReturnFullUrlLocation(url);
  3588. var saveAndLoadImage = function () {
  3589. if (!_this.hasReachedQuota && _this.db !== null) {
  3590. // the texture is not yet in the DB, let's try to save it
  3591. _this._saveImageIntoDBAsync(completeURL, image);
  3592. }
  3593. else {
  3594. image.src = url;
  3595. }
  3596. };
  3597. if (!this.mustUpdateRessources) {
  3598. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3599. }
  3600. else {
  3601. saveAndLoadImage();
  3602. }
  3603. };
  3604. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3605. if (this.isSupported && this.db !== null) {
  3606. var texture;
  3607. var transaction = this.db.transaction(["textures"]);
  3608. transaction.onabort = function (event) {
  3609. image.src = url;
  3610. };
  3611. transaction.oncomplete = function (event) {
  3612. var blobTextureURL;
  3613. if (texture) {
  3614. var URL = window.URL || window.webkitURL;
  3615. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3616. image.onerror = function () {
  3617. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3618. image.src = url;
  3619. };
  3620. image.src = blobTextureURL;
  3621. }
  3622. else {
  3623. notInDBCallback();
  3624. }
  3625. };
  3626. var getRequest = transaction.objectStore("textures").get(url);
  3627. getRequest.onsuccess = function (event) {
  3628. texture = (event.target).result;
  3629. };
  3630. getRequest.onerror = function (event) {
  3631. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3632. image.src = url;
  3633. };
  3634. }
  3635. else {
  3636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3637. image.src = url;
  3638. }
  3639. };
  3640. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3641. var _this = this;
  3642. if (this.isSupported) {
  3643. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3644. var generateBlobUrl = function () {
  3645. var blobTextureURL;
  3646. if (blob) {
  3647. var URL = window.URL || window.webkitURL;
  3648. try {
  3649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3650. }
  3651. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3652. catch (ex) {
  3653. blobTextureURL = URL.createObjectURL(blob);
  3654. }
  3655. }
  3656. image.src = blobTextureURL;
  3657. };
  3658. if (Database.IsUASupportingBlobStorage) {
  3659. var xhr = new XMLHttpRequest(), blob;
  3660. xhr.open("GET", url, true);
  3661. xhr.responseType = "blob";
  3662. xhr.addEventListener("load", function () {
  3663. if (xhr.status === 200) {
  3664. // Blob as response (XHR2)
  3665. blob = xhr.response;
  3666. var transaction = _this.db.transaction(["textures"], "readwrite");
  3667. // the transaction could abort because of a QuotaExceededError error
  3668. transaction.onabort = function (event) {
  3669. try {
  3670. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3671. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3672. this.hasReachedQuota = true;
  3673. }
  3674. }
  3675. catch (ex) { }
  3676. generateBlobUrl();
  3677. };
  3678. transaction.oncomplete = function (event) {
  3679. generateBlobUrl();
  3680. };
  3681. var newTexture = { textureUrl: url, data: blob };
  3682. try {
  3683. // Put the blob into the dabase
  3684. var addRequest = transaction.objectStore("textures").put(newTexture);
  3685. addRequest.onsuccess = function (event) {
  3686. };
  3687. addRequest.onerror = function (event) {
  3688. generateBlobUrl();
  3689. };
  3690. }
  3691. catch (ex) {
  3692. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3693. if (ex.code === 25) {
  3694. Database.IsUASupportingBlobStorage = false;
  3695. }
  3696. image.src = url;
  3697. }
  3698. }
  3699. else {
  3700. image.src = url;
  3701. }
  3702. }, false);
  3703. xhr.addEventListener("error", function (event) {
  3704. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3705. image.src = url;
  3706. }, false);
  3707. xhr.send();
  3708. }
  3709. else {
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3715. image.src = url;
  3716. }
  3717. };
  3718. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3719. var _this = this;
  3720. var updateVersion = function (event) {
  3721. // the version is not yet in the DB or we need to update it
  3722. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3723. };
  3724. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3725. };
  3726. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3727. var _this = this;
  3728. if (this.isSupported) {
  3729. var version;
  3730. try {
  3731. var transaction = this.db.transaction(["versions"]);
  3732. transaction.oncomplete = function (event) {
  3733. if (version) {
  3734. // If the version in the JSON file is > than the version in DB
  3735. if (_this.manifestVersionFound > version.data) {
  3736. _this.mustUpdateRessources = true;
  3737. updateInDBCallback();
  3738. }
  3739. else {
  3740. callback(version.data);
  3741. }
  3742. }
  3743. else {
  3744. _this.mustUpdateRessources = true;
  3745. updateInDBCallback();
  3746. }
  3747. };
  3748. transaction.onabort = function (event) {
  3749. callback(-1);
  3750. };
  3751. var getRequest = transaction.objectStore("versions").get(url);
  3752. getRequest.onsuccess = function (event) {
  3753. version = (event.target).result;
  3754. };
  3755. getRequest.onerror = function (event) {
  3756. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3757. callback(-1);
  3758. };
  3759. }
  3760. catch (ex) {
  3761. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3762. callback(-1);
  3763. }
  3764. }
  3765. else {
  3766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3767. callback(-1);
  3768. }
  3769. };
  3770. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3771. var _this = this;
  3772. if (this.isSupported && !this.hasReachedQuota) {
  3773. try {
  3774. // Open a transaction to the database
  3775. var transaction = this.db.transaction(["versions"], "readwrite");
  3776. // the transaction could abort because of a QuotaExceededError error
  3777. transaction.onabort = function (event) {
  3778. try {
  3779. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3780. _this.hasReachedQuota = true;
  3781. }
  3782. }
  3783. catch (ex) { }
  3784. callback(-1);
  3785. };
  3786. transaction.oncomplete = function (event) {
  3787. callback(_this.manifestVersionFound);
  3788. };
  3789. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3790. // Put the scene into the database
  3791. var addRequest = transaction.objectStore("versions").put(newVersion);
  3792. addRequest.onsuccess = function (event) {
  3793. };
  3794. addRequest.onerror = function (event) {
  3795. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3796. };
  3797. }
  3798. catch (ex) {
  3799. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3800. callback(-1);
  3801. }
  3802. }
  3803. else {
  3804. callback(-1);
  3805. }
  3806. };
  3807. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3808. var _this = this;
  3809. var completeUrl = Database.ReturnFullUrlLocation(url);
  3810. var saveAndLoadFile = function (event) {
  3811. // the scene is not yet in the DB, let's try to save it
  3812. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3813. };
  3814. this._checkVersionFromDB(completeUrl, function (version) {
  3815. if (version !== -1) {
  3816. if (!_this.mustUpdateRessources) {
  3817. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3818. }
  3819. else {
  3820. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3821. }
  3822. }
  3823. else {
  3824. errorCallback();
  3825. }
  3826. });
  3827. };
  3828. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3829. if (this.isSupported) {
  3830. var targetStore;
  3831. if (url.indexOf(".babylon") !== -1) {
  3832. targetStore = "scenes";
  3833. }
  3834. else {
  3835. targetStore = "textures";
  3836. }
  3837. var file;
  3838. var transaction = this.db.transaction([targetStore]);
  3839. transaction.oncomplete = function (event) {
  3840. if (file) {
  3841. callback(file.data);
  3842. }
  3843. else {
  3844. notInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. notInDBCallback();
  3849. };
  3850. var getRequest = transaction.objectStore(targetStore).get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. file = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3856. notInDBCallback();
  3857. };
  3858. }
  3859. else {
  3860. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3861. callback();
  3862. }
  3863. };
  3864. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3865. var _this = this;
  3866. if (this.isSupported) {
  3867. var targetStore;
  3868. if (url.indexOf(".babylon") !== -1) {
  3869. targetStore = "scenes";
  3870. }
  3871. else {
  3872. targetStore = "textures";
  3873. }
  3874. // Create XHR
  3875. var xhr = new XMLHttpRequest(), fileData;
  3876. xhr.open("GET", url, true);
  3877. if (useArrayBuffer) {
  3878. xhr.responseType = "arraybuffer";
  3879. }
  3880. xhr.onprogress = progressCallback;
  3881. xhr.addEventListener("load", function () {
  3882. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3883. // Blob as response (XHR2)
  3884. //fileData = xhr.responseText;
  3885. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3886. if (!_this.hasReachedQuota) {
  3887. // Open a transaction to the database
  3888. var transaction = _this.db.transaction([targetStore], "readwrite");
  3889. // the transaction could abort because of a QuotaExceededError error
  3890. transaction.onabort = function (event) {
  3891. try {
  3892. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3893. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3894. this.hasReachedQuota = true;
  3895. }
  3896. }
  3897. catch (ex) { }
  3898. callback(fileData);
  3899. };
  3900. transaction.oncomplete = function (event) {
  3901. callback(fileData);
  3902. };
  3903. var newFile;
  3904. if (targetStore === "scenes") {
  3905. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3906. }
  3907. else {
  3908. newFile = { textureUrl: url, data: fileData };
  3909. }
  3910. try {
  3911. // Put the scene into the database
  3912. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3913. addRequest.onsuccess = function (event) {
  3914. };
  3915. addRequest.onerror = function (event) {
  3916. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3917. };
  3918. }
  3919. catch (ex) {
  3920. callback(fileData);
  3921. }
  3922. }
  3923. else {
  3924. callback(fileData);
  3925. }
  3926. }
  3927. else {
  3928. callback();
  3929. }
  3930. }, false);
  3931. xhr.addEventListener("error", function (event) {
  3932. BABYLON.Tools.Error("error on XHR request.");
  3933. callback();
  3934. }, false);
  3935. xhr.send();
  3936. }
  3937. else {
  3938. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3939. callback();
  3940. }
  3941. };
  3942. Database.IsUASupportingBlobStorage = true;
  3943. Database.IDBStorageEnabled = true;
  3944. Database.parseURL = function (url) {
  3945. var a = document.createElement('a');
  3946. a.href = url;
  3947. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3948. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3949. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3950. return absLocation;
  3951. };
  3952. Database.ReturnFullUrlLocation = function (url) {
  3953. if (url.indexOf("http:/") === -1) {
  3954. return (Database.parseURL(window.location.href) + url);
  3955. }
  3956. else {
  3957. return url;
  3958. }
  3959. };
  3960. return Database;
  3961. })();
  3962. BABYLON.Database = Database;
  3963. })(BABYLON || (BABYLON = {}));
  3964. var BABYLON;
  3965. (function (BABYLON) {
  3966. var Internals;
  3967. (function (Internals) {
  3968. /*
  3969. * Based on jsTGALoader - Javascript loader for TGA file
  3970. * By Vincent Thibault
  3971. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3972. */
  3973. var TGATools = (function () {
  3974. function TGATools() {
  3975. }
  3976. TGATools.GetTGAHeader = function (data) {
  3977. var offset = 0;
  3978. var header = {
  3979. id_length: data[offset++],
  3980. colormap_type: data[offset++],
  3981. image_type: data[offset++],
  3982. colormap_index: data[offset++] | data[offset++] << 8,
  3983. colormap_length: data[offset++] | data[offset++] << 8,
  3984. colormap_size: data[offset++],
  3985. origin: [
  3986. data[offset++] | data[offset++] << 8,
  3987. data[offset++] | data[offset++] << 8
  3988. ],
  3989. width: data[offset++] | data[offset++] << 8,
  3990. height: data[offset++] | data[offset++] << 8,
  3991. pixel_size: data[offset++],
  3992. flags: data[offset++]
  3993. };
  3994. return header;
  3995. };
  3996. TGATools.UploadContent = function (gl, data) {
  3997. // Not enough data to contain header ?
  3998. if (data.length < 19) {
  3999. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4000. return;
  4001. }
  4002. // Read Header
  4003. var offset = 18;
  4004. var header = TGATools.GetTGAHeader(data);
  4005. // Assume it's a valid Targa file.
  4006. if (header.id_length + offset > data.length) {
  4007. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4008. return;
  4009. }
  4010. // Skip not needed data
  4011. offset += header.id_length;
  4012. var use_rle = false;
  4013. var use_pal = false;
  4014. var use_rgb = false;
  4015. var use_grey = false;
  4016. // Get some informations.
  4017. switch (header.image_type) {
  4018. case TGATools._TYPE_RLE_INDEXED:
  4019. use_rle = true;
  4020. case TGATools._TYPE_INDEXED:
  4021. use_pal = true;
  4022. break;
  4023. case TGATools._TYPE_RLE_RGB:
  4024. use_rle = true;
  4025. case TGATools._TYPE_RGB:
  4026. use_rgb = true;
  4027. break;
  4028. case TGATools._TYPE_RLE_GREY:
  4029. use_rle = true;
  4030. case TGATools._TYPE_GREY:
  4031. use_grey = true;
  4032. break;
  4033. }
  4034. var pixel_data;
  4035. var numAlphaBits = header.flags & 0xf;
  4036. var pixel_size = header.pixel_size >> 3;
  4037. var pixel_total = header.width * header.height * pixel_size;
  4038. // Read palettes
  4039. var palettes;
  4040. if (use_pal) {
  4041. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4042. }
  4043. // Read LRE
  4044. if (use_rle) {
  4045. pixel_data = new Uint8Array(pixel_total);
  4046. var c, count, i;
  4047. var localOffset = 0;
  4048. var pixels = new Uint8Array(pixel_size);
  4049. while (offset < pixel_total && localOffset < pixel_total) {
  4050. c = data[offset++];
  4051. count = (c & 0x7f) + 1;
  4052. // RLE pixels
  4053. if (c & 0x80) {
  4054. // Bind pixel tmp array
  4055. for (i = 0; i < pixel_size; ++i) {
  4056. pixels[i] = data[offset++];
  4057. }
  4058. // Copy pixel array
  4059. for (i = 0; i < count; ++i) {
  4060. pixel_data.set(pixels, localOffset + i * pixel_size);
  4061. }
  4062. localOffset += pixel_size * count;
  4063. }
  4064. else {
  4065. count *= pixel_size;
  4066. for (i = 0; i < count; ++i) {
  4067. pixel_data[localOffset + i] = data[offset++];
  4068. }
  4069. localOffset += count;
  4070. }
  4071. }
  4072. }
  4073. else {
  4074. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4075. }
  4076. // Load to texture
  4077. var x_start, y_start, x_step, y_step, y_end, x_end;
  4078. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4079. default:
  4080. case TGATools._ORIGIN_UL:
  4081. x_start = 0;
  4082. x_step = 1;
  4083. x_end = header.width;
  4084. y_start = 0;
  4085. y_step = 1;
  4086. y_end = header.height;
  4087. break;
  4088. case TGATools._ORIGIN_BL:
  4089. x_start = 0;
  4090. x_step = 1;
  4091. x_end = header.width;
  4092. y_start = header.height - 1;
  4093. y_step = -1;
  4094. y_end = -1;
  4095. break;
  4096. case TGATools._ORIGIN_UR:
  4097. x_start = header.width - 1;
  4098. x_step = -1;
  4099. x_end = -1;
  4100. y_start = 0;
  4101. y_step = 1;
  4102. y_end = header.height;
  4103. break;
  4104. case TGATools._ORIGIN_BR:
  4105. x_start = header.width - 1;
  4106. x_step = -1;
  4107. x_end = -1;
  4108. y_start = header.height - 1;
  4109. y_step = -1;
  4110. y_end = -1;
  4111. break;
  4112. }
  4113. // Load the specify method
  4114. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4115. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4116. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4117. };
  4118. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4119. var image = pixel_data, colormap = palettes;
  4120. var width = header.width, height = header.height;
  4121. var color, i = 0, x, y;
  4122. var imageData = new Uint8Array(width * height * 4);
  4123. for (y = y_start; y !== y_end; y += y_step) {
  4124. for (x = x_start; x !== x_end; x += x_step, i++) {
  4125. color = image[i];
  4126. imageData[(x + width * y) * 4 + 3] = 255;
  4127. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4128. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4129. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4130. }
  4131. }
  4132. return imageData;
  4133. };
  4134. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4135. var image = pixel_data;
  4136. var width = header.width, height = header.height;
  4137. var color, i = 0, x, y;
  4138. var imageData = new Uint8Array(width * height * 4);
  4139. for (y = y_start; y !== y_end; y += y_step) {
  4140. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4141. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4142. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4143. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4144. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4145. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4146. }
  4147. }
  4148. return imageData;
  4149. };
  4150. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4151. var image = pixel_data;
  4152. var width = header.width, height = header.height;
  4153. var i = 0, x, y;
  4154. var imageData = new Uint8Array(width * height * 4);
  4155. for (y = y_start; y !== y_end; y += y_step) {
  4156. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4157. imageData[(x + width * y) * 4 + 3] = 255;
  4158. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4159. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4160. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4161. }
  4162. }
  4163. return imageData;
  4164. };
  4165. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4166. var image = pixel_data;
  4167. var width = header.width, height = header.height;
  4168. var i = 0, x, y;
  4169. var imageData = new Uint8Array(width * height * 4);
  4170. for (y = y_start; y !== y_end; y += y_step) {
  4171. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4176. }
  4177. }
  4178. return imageData;
  4179. };
  4180. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4181. var image = pixel_data;
  4182. var width = header.width, height = header.height;
  4183. var color, i = 0, x, y;
  4184. var imageData = new Uint8Array(width * height * 4);
  4185. for (y = y_start; y !== y_end; y += y_step) {
  4186. for (x = x_start; x !== x_end; x += x_step, i++) {
  4187. color = image[i];
  4188. imageData[(x + width * y) * 4 + 0] = color;
  4189. imageData[(x + width * y) * 4 + 1] = color;
  4190. imageData[(x + width * y) * 4 + 2] = color;
  4191. imageData[(x + width * y) * 4 + 3] = 255;
  4192. }
  4193. }
  4194. return imageData;
  4195. };
  4196. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4197. var image = pixel_data;
  4198. var width = header.width, height = header.height;
  4199. var i = 0, x, y;
  4200. var imageData = new Uint8Array(width * height * 4);
  4201. for (y = y_start; y !== y_end; y += y_step) {
  4202. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4203. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4204. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4205. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4206. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4207. }
  4208. }
  4209. return imageData;
  4210. };
  4211. TGATools._TYPE_NO_DATA = 0;
  4212. TGATools._TYPE_INDEXED = 1;
  4213. TGATools._TYPE_RGB = 2;
  4214. TGATools._TYPE_GREY = 3;
  4215. TGATools._TYPE_RLE_INDEXED = 9;
  4216. TGATools._TYPE_RLE_RGB = 10;
  4217. TGATools._TYPE_RLE_GREY = 11;
  4218. TGATools._ORIGIN_MASK = 0x30;
  4219. TGATools._ORIGIN_SHIFT = 0x04;
  4220. TGATools._ORIGIN_BL = 0x00;
  4221. TGATools._ORIGIN_BR = 0x01;
  4222. TGATools._ORIGIN_UL = 0x02;
  4223. TGATools._ORIGIN_UR = 0x03;
  4224. return TGATools;
  4225. })();
  4226. Internals.TGATools = TGATools;
  4227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4228. })(BABYLON || (BABYLON = {}));
  4229. var BABYLON;
  4230. (function (BABYLON) {
  4231. var SmartArray = (function () {
  4232. function SmartArray(capacity) {
  4233. this.length = 0;
  4234. this._duplicateId = 0;
  4235. this.data = new Array(capacity);
  4236. this._id = SmartArray._GlobalId++;
  4237. }
  4238. SmartArray.prototype.push = function (value) {
  4239. this.data[this.length++] = value;
  4240. if (this.length > this.data.length) {
  4241. this.data.length *= 2;
  4242. }
  4243. if (!value.__smartArrayFlags) {
  4244. value.__smartArrayFlags = {};
  4245. }
  4246. value.__smartArrayFlags[this._id] = this._duplicateId;
  4247. };
  4248. SmartArray.prototype.pushNoDuplicate = function (value) {
  4249. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4250. return false;
  4251. }
  4252. this.push(value);
  4253. return true;
  4254. };
  4255. SmartArray.prototype.sort = function (compareFn) {
  4256. this.data.sort(compareFn);
  4257. };
  4258. SmartArray.prototype.reset = function () {
  4259. this.length = 0;
  4260. this._duplicateId++;
  4261. };
  4262. SmartArray.prototype.concat = function (array) {
  4263. if (array.length === 0) {
  4264. return;
  4265. }
  4266. if (this.length + array.length > this.data.length) {
  4267. this.data.length = (this.length + array.length) * 2;
  4268. }
  4269. for (var index = 0; index < array.length; index++) {
  4270. this.data[this.length++] = (array.data || array)[index];
  4271. }
  4272. };
  4273. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4274. if (array.length === 0) {
  4275. return;
  4276. }
  4277. if (this.length + array.length > this.data.length) {
  4278. this.data.length = (this.length + array.length) * 2;
  4279. }
  4280. for (var index = 0; index < array.length; index++) {
  4281. var item = (array.data || array)[index];
  4282. this.pushNoDuplicate(item);
  4283. }
  4284. };
  4285. SmartArray.prototype.indexOf = function (value) {
  4286. var position = this.data.indexOf(value);
  4287. if (position >= this.length) {
  4288. return -1;
  4289. }
  4290. return position;
  4291. };
  4292. // Statics
  4293. SmartArray._GlobalId = 0;
  4294. return SmartArray;
  4295. })();
  4296. BABYLON.SmartArray = SmartArray;
  4297. })(BABYLON || (BABYLON = {}));
  4298. var BABYLON;
  4299. (function (BABYLON) {
  4300. /**
  4301. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4302. * The underlying implementation relies on an associative array to ensure the best performances.
  4303. * The value can be anything including 'null' but except 'undefined'
  4304. */
  4305. var StringDictionary = (function () {
  4306. function StringDictionary() {
  4307. this._count = 0;
  4308. this._data = {};
  4309. }
  4310. /**
  4311. * Get a value based from its key
  4312. * @param key the given key to get the matching value from
  4313. * @return the value if found, otherwise undefined is returned
  4314. */
  4315. StringDictionary.prototype.get = function (key) {
  4316. var val = this._data[key];
  4317. if (val !== undefined) {
  4318. return val;
  4319. }
  4320. return undefined;
  4321. };
  4322. /**
  4323. * Get a value from its key or add it if it doesn't exist.
  4324. * This method will ensure you that a given key/data will be present in the dictionary.
  4325. * @param key the given key to get the matching value from
  4326. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4327. * The factory will only be invoked if there's no data for the given key.
  4328. * @return the value corresponding to the key.
  4329. */
  4330. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4331. var val = this.get(key);
  4332. if (val !== undefined) {
  4333. return val;
  4334. }
  4335. val = factory(key);
  4336. if (val) {
  4337. this.add(key, val);
  4338. }
  4339. return val;
  4340. };
  4341. /**
  4342. * Get a value from its key if present in the dictionary otherwise add it
  4343. * @param key the key to get the value from
  4344. * @param val if there's no such key/value pair in the dictionary add it with this value
  4345. * @return the value corresponding to the key
  4346. */
  4347. StringDictionary.prototype.getOrAdd = function (key, val) {
  4348. var curVal = this.get(key);
  4349. if (curVal !== undefined) {
  4350. return curVal;
  4351. }
  4352. this.add(key, val);
  4353. return val;
  4354. };
  4355. /**
  4356. * Check if there's a given key in the dictionary
  4357. * @param key the key to check for
  4358. * @return true if the key is present, false otherwise
  4359. */
  4360. StringDictionary.prototype.contains = function (key) {
  4361. return this._data[key] !== undefined;
  4362. };
  4363. /**
  4364. * Add a new key and its corresponding value
  4365. * @param key the key to add
  4366. * @param value the value corresponding to the key
  4367. * @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
  4368. */
  4369. StringDictionary.prototype.add = function (key, value) {
  4370. if (this._data[key] !== undefined) {
  4371. return false;
  4372. }
  4373. this._data[key] = value;
  4374. ++this._count;
  4375. return true;
  4376. };
  4377. StringDictionary.prototype.set = function (key, value) {
  4378. if (this._data[key] === undefined) {
  4379. return false;
  4380. }
  4381. this._data[key] = value;
  4382. return true;
  4383. };
  4384. /**
  4385. * Remove a key/value from the dictionary.
  4386. * @param key the key to remove
  4387. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4388. */
  4389. StringDictionary.prototype.remove = function (key) {
  4390. if (this.contains(key)) {
  4391. delete this._data[key];
  4392. --this._count;
  4393. return true;
  4394. }
  4395. return false;
  4396. };
  4397. /**
  4398. * Clear the whole content of the dictionary
  4399. */
  4400. StringDictionary.prototype.clear = function () {
  4401. this._data = {};
  4402. this._count = 0;
  4403. };
  4404. Object.defineProperty(StringDictionary.prototype, "count", {
  4405. get: function () {
  4406. return this._count;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Execute a callback on each key/val of the dictionary.
  4413. * Note that you can remove any element in this dictionary in the callback implementation
  4414. * @param callback the callback to execute on a given key/value pair
  4415. */
  4416. StringDictionary.prototype.forEach = function (callback) {
  4417. for (var cur in this._data) {
  4418. var val = this._data[cur];
  4419. callback(cur, val);
  4420. }
  4421. };
  4422. /**
  4423. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4424. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4425. * Note that you can remove any element in this dictionary in the callback implementation
  4426. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4427. */
  4428. StringDictionary.prototype.first = function (callback) {
  4429. for (var cur in this._data) {
  4430. var val = this._data[cur];
  4431. var res = callback(cur, val);
  4432. if (res) {
  4433. return res;
  4434. }
  4435. }
  4436. return null;
  4437. };
  4438. return StringDictionary;
  4439. })();
  4440. BABYLON.StringDictionary = StringDictionary;
  4441. })(BABYLON || (BABYLON = {}));
  4442. var BABYLON;
  4443. (function (BABYLON) {
  4444. // Screenshots
  4445. var screenshotCanvas;
  4446. var cloneValue = function (source, destinationObject) {
  4447. if (!source)
  4448. return null;
  4449. if (source instanceof BABYLON.Mesh) {
  4450. return null;
  4451. }
  4452. if (source instanceof BABYLON.SubMesh) {
  4453. return source.clone(destinationObject);
  4454. }
  4455. else if (source.clone) {
  4456. return source.clone();
  4457. }
  4458. return null;
  4459. };
  4460. var Tools = (function () {
  4461. function Tools() {
  4462. }
  4463. Tools.Instantiate = function (className) {
  4464. var arr = className.split(".");
  4465. var fn = (window || this);
  4466. for (var i = 0, len = arr.length; i < len; i++) {
  4467. fn = fn[arr[i]];
  4468. }
  4469. if (typeof fn !== "function") {
  4470. return null;
  4471. }
  4472. return fn;
  4473. };
  4474. Tools.SetImmediate = function (action) {
  4475. if (window.setImmediate) {
  4476. window.setImmediate(action);
  4477. }
  4478. else {
  4479. setTimeout(action, 1);
  4480. }
  4481. };
  4482. Tools.IsExponentOfTwo = function (value) {
  4483. var count = 1;
  4484. do {
  4485. count *= 2;
  4486. } while (count < value);
  4487. return count === value;
  4488. };
  4489. Tools.GetExponentOfTwo = function (value, max) {
  4490. var count = 1;
  4491. do {
  4492. count *= 2;
  4493. } while (count < value);
  4494. if (count > max)
  4495. count = max;
  4496. return count;
  4497. };
  4498. Tools.GetFilename = function (path) {
  4499. var index = path.lastIndexOf("/");
  4500. if (index < 0)
  4501. return path;
  4502. return path.substring(index + 1);
  4503. };
  4504. Tools.GetDOMTextContent = function (element) {
  4505. var result = "";
  4506. var child = element.firstChild;
  4507. while (child) {
  4508. if (child.nodeType === 3) {
  4509. result += child.textContent;
  4510. }
  4511. child = child.nextSibling;
  4512. }
  4513. return result;
  4514. };
  4515. Tools.ToDegrees = function (angle) {
  4516. return angle * 180 / Math.PI;
  4517. };
  4518. Tools.ToRadians = function (angle) {
  4519. return angle * Math.PI / 180;
  4520. };
  4521. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4522. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4523. var output = "";
  4524. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4525. var i = 0;
  4526. var bytes = new Uint8Array(buffer);
  4527. while (i < bytes.length) {
  4528. chr1 = bytes[i++];
  4529. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4530. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4531. enc1 = chr1 >> 2;
  4532. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4533. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4534. enc4 = chr3 & 63;
  4535. if (isNaN(chr2)) {
  4536. enc3 = enc4 = 64;
  4537. }
  4538. else if (isNaN(chr3)) {
  4539. enc4 = 64;
  4540. }
  4541. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4542. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4543. }
  4544. return "data:image/png;base64," + output;
  4545. };
  4546. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4547. if (bias === void 0) { bias = null; }
  4548. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4549. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4550. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4551. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4552. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4553. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4554. }
  4555. if (bias) {
  4556. minimum.x -= minimum.x * bias.x + bias.y;
  4557. minimum.y -= minimum.y * bias.x + bias.y;
  4558. minimum.z -= minimum.z * bias.x + bias.y;
  4559. maximum.x += maximum.x * bias.x + bias.y;
  4560. maximum.y += maximum.y * bias.x + bias.y;
  4561. maximum.z += maximum.z * bias.x + bias.y;
  4562. }
  4563. return {
  4564. minimum: minimum,
  4565. maximum: maximum
  4566. };
  4567. };
  4568. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4569. if (bias === void 0) { bias = null; }
  4570. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4571. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4572. if (!stride) {
  4573. stride = 3;
  4574. }
  4575. for (var index = start; index < start + count; index++) {
  4576. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4577. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4578. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4579. }
  4580. if (bias) {
  4581. minimum.x -= minimum.x * bias.x + bias.y;
  4582. minimum.y -= minimum.y * bias.x + bias.y;
  4583. minimum.z -= minimum.z * bias.x + bias.y;
  4584. maximum.x += maximum.x * bias.x + bias.y;
  4585. maximum.y += maximum.y * bias.x + bias.y;
  4586. maximum.z += maximum.z * bias.x + bias.y;
  4587. }
  4588. return {
  4589. minimum: minimum,
  4590. maximum: maximum
  4591. };
  4592. };
  4593. Tools.Vector2ArrayFeeder = function (array) {
  4594. return function (index) {
  4595. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4596. var length = isFloatArray ? array.length / 2 : array.length;
  4597. if (index >= length) {
  4598. return null;
  4599. }
  4600. if (isFloatArray) {
  4601. var fa = array;
  4602. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4603. }
  4604. var a = array;
  4605. return a[index];
  4606. };
  4607. };
  4608. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4609. if (bias === void 0) { bias = null; }
  4610. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4611. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4612. var i = 0;
  4613. var cur = feeder(i++);
  4614. while (cur) {
  4615. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4616. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4617. cur = feeder(i++);
  4618. }
  4619. if (bias) {
  4620. minimum.x -= minimum.x * bias.x + bias.y;
  4621. minimum.y -= minimum.y * bias.x + bias.y;
  4622. maximum.x += maximum.x * bias.x + bias.y;
  4623. maximum.y += maximum.y * bias.x + bias.y;
  4624. }
  4625. return {
  4626. minimum: minimum,
  4627. maximum: maximum
  4628. };
  4629. };
  4630. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4631. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4632. return undefined;
  4633. return Array.isArray(obj) ? obj : [obj];
  4634. };
  4635. // Misc.
  4636. Tools.GetPointerPrefix = function () {
  4637. var eventPrefix = "pointer";
  4638. // Check if pointer events are supported
  4639. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4640. eventPrefix = "mouse";
  4641. }
  4642. return eventPrefix;
  4643. };
  4644. Tools.QueueNewFrame = function (func) {
  4645. if (window.requestAnimationFrame)
  4646. window.requestAnimationFrame(func);
  4647. else if (window.msRequestAnimationFrame)
  4648. window.msRequestAnimationFrame(func);
  4649. else if (window.webkitRequestAnimationFrame)
  4650. window.webkitRequestAnimationFrame(func);
  4651. else if (window.mozRequestAnimationFrame)
  4652. window.mozRequestAnimationFrame(func);
  4653. else if (window.oRequestAnimationFrame)
  4654. window.oRequestAnimationFrame(func);
  4655. else {
  4656. window.setTimeout(func, 16);
  4657. }
  4658. };
  4659. Tools.RequestFullscreen = function (element, options) {
  4660. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4661. if (!requestFunction)
  4662. return;
  4663. requestFunction.call(element, options);
  4664. };
  4665. Tools.ExitFullscreen = function () {
  4666. if (document.exitFullscreen) {
  4667. document.exitFullscreen();
  4668. }
  4669. else if (document.mozCancelFullScreen) {
  4670. document.mozCancelFullScreen();
  4671. }
  4672. else if (document.webkitCancelFullScreen) {
  4673. document.webkitCancelFullScreen();
  4674. }
  4675. else if (document.msCancelFullScreen) {
  4676. document.msCancelFullScreen();
  4677. }
  4678. };
  4679. // External files
  4680. Tools.CleanUrl = function (url) {
  4681. url = url.replace(/#/mg, "%23");
  4682. return url;
  4683. };
  4684. Tools.LoadImage = function (url, onload, onerror, database) {
  4685. if (url instanceof ArrayBuffer) {
  4686. url = Tools.EncodeArrayBufferTobase64(url);
  4687. }
  4688. url = Tools.CleanUrl(url);
  4689. var img = new Image();
  4690. if (url.substr(0, 5) !== "data:") {
  4691. if (Tools.CorsBehavior) {
  4692. switch (typeof (Tools.CorsBehavior)) {
  4693. case "function":
  4694. var result = Tools.CorsBehavior(url);
  4695. if (result) {
  4696. img.crossOrigin = result;
  4697. }
  4698. break;
  4699. case "string":
  4700. default:
  4701. img.crossOrigin = Tools.CorsBehavior;
  4702. break;
  4703. }
  4704. }
  4705. }
  4706. img.onload = function () {
  4707. onload(img);
  4708. };
  4709. img.onerror = function (err) {
  4710. Tools.Error("Error while trying to load texture: " + url);
  4711. if (Tools.UseFallbackTexture) {
  4712. 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";
  4713. onload(img);
  4714. }
  4715. else {
  4716. onerror();
  4717. }
  4718. };
  4719. var noIndexedDB = function () {
  4720. img.src = url;
  4721. };
  4722. var loadFromIndexedDB = function () {
  4723. database.loadImageFromDB(url, img);
  4724. };
  4725. //ANY database to do!
  4726. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4727. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4728. }
  4729. else {
  4730. if (url.indexOf("file:") === -1) {
  4731. noIndexedDB();
  4732. }
  4733. else {
  4734. try {
  4735. var textureName = url.substring(5).toLowerCase();
  4736. var blobURL;
  4737. try {
  4738. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4739. }
  4740. catch (ex) {
  4741. // Chrome doesn't support oneTimeOnly parameter
  4742. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4743. }
  4744. img.src = blobURL;
  4745. }
  4746. catch (e) {
  4747. img.src = null;
  4748. }
  4749. }
  4750. }
  4751. return img;
  4752. };
  4753. //ANY
  4754. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4755. url = Tools.CleanUrl(url);
  4756. var noIndexedDB = function () {
  4757. var request = new XMLHttpRequest();
  4758. var loadUrl = Tools.BaseUrl + url;
  4759. request.open('GET', loadUrl, true);
  4760. if (useArrayBuffer) {
  4761. request.responseType = "arraybuffer";
  4762. }
  4763. request.onprogress = progressCallBack;
  4764. request.onreadystatechange = function () {
  4765. if (request.readyState === 4) {
  4766. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4767. callback(!useArrayBuffer ? request.responseText : request.response);
  4768. }
  4769. else {
  4770. if (onError) {
  4771. onError();
  4772. }
  4773. else {
  4774. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4775. }
  4776. }
  4777. }
  4778. };
  4779. request.send(null);
  4780. };
  4781. var loadFromIndexedDB = function () {
  4782. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4783. };
  4784. if (url.indexOf("file:") !== -1) {
  4785. var fileName = url.substring(5).toLowerCase();
  4786. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4787. }
  4788. else {
  4789. // Caching all files
  4790. if (database && database.enableSceneOffline) {
  4791. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4792. }
  4793. else {
  4794. noIndexedDB();
  4795. }
  4796. }
  4797. };
  4798. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4799. var reader = new FileReader();
  4800. reader.onload = function (e) {
  4801. //target doesn't have result from ts 1.3
  4802. callback(e.target['result']);
  4803. };
  4804. reader.onprogress = progressCallback;
  4805. reader.readAsDataURL(fileToLoad);
  4806. };
  4807. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4808. var reader = new FileReader();
  4809. reader.onerror = function (e) {
  4810. Tools.Log("Error while reading file: " + fileToLoad.name);
  4811. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4812. };
  4813. reader.onload = function (e) {
  4814. //target doesn't have result from ts 1.3
  4815. callback(e.target['result']);
  4816. };
  4817. reader.onprogress = progressCallBack;
  4818. if (!useArrayBuffer) {
  4819. // Asynchronous read
  4820. reader.readAsText(fileToLoad);
  4821. }
  4822. else {
  4823. reader.readAsArrayBuffer(fileToLoad);
  4824. }
  4825. };
  4826. //returns a downloadable url to a file content.
  4827. Tools.FileAsURL = function (content) {
  4828. var fileBlob = new Blob([content]);
  4829. var url = window.URL || window.webkitURL;
  4830. var link = url.createObjectURL(fileBlob);
  4831. return link;
  4832. };
  4833. // Misc.
  4834. Tools.Format = function (value, decimals) {
  4835. if (decimals === void 0) { decimals = 2; }
  4836. return value.toFixed(decimals);
  4837. };
  4838. Tools.CheckExtends = function (v, min, max) {
  4839. if (v.x < min.x)
  4840. min.x = v.x;
  4841. if (v.y < min.y)
  4842. min.y = v.y;
  4843. if (v.z < min.z)
  4844. min.z = v.z;
  4845. if (v.x > max.x)
  4846. max.x = v.x;
  4847. if (v.y > max.y)
  4848. max.y = v.y;
  4849. if (v.z > max.z)
  4850. max.z = v.z;
  4851. };
  4852. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4853. for (var prop in source) {
  4854. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4855. continue;
  4856. }
  4857. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4858. continue;
  4859. }
  4860. var sourceValue = source[prop];
  4861. var typeOfSourceValue = typeof sourceValue;
  4862. if (typeOfSourceValue === "function") {
  4863. continue;
  4864. }
  4865. if (typeOfSourceValue === "object") {
  4866. if (sourceValue instanceof Array) {
  4867. destination[prop] = [];
  4868. if (sourceValue.length > 0) {
  4869. if (typeof sourceValue[0] == "object") {
  4870. for (var index = 0; index < sourceValue.length; index++) {
  4871. var clonedValue = cloneValue(sourceValue[index], destination);
  4872. if (destination[prop].indexOf(clonedValue) === -1) {
  4873. destination[prop].push(clonedValue);
  4874. }
  4875. }
  4876. }
  4877. else {
  4878. destination[prop] = sourceValue.slice(0);
  4879. }
  4880. }
  4881. }
  4882. else {
  4883. destination[prop] = cloneValue(sourceValue, destination);
  4884. }
  4885. }
  4886. else {
  4887. destination[prop] = sourceValue;
  4888. }
  4889. }
  4890. };
  4891. Tools.IsEmpty = function (obj) {
  4892. for (var i in obj) {
  4893. return false;
  4894. }
  4895. return true;
  4896. };
  4897. Tools.RegisterTopRootEvents = function (events) {
  4898. for (var index = 0; index < events.length; index++) {
  4899. var event = events[index];
  4900. window.addEventListener(event.name, event.handler, false);
  4901. try {
  4902. if (window.parent) {
  4903. window.parent.addEventListener(event.name, event.handler, false);
  4904. }
  4905. }
  4906. catch (e) {
  4907. }
  4908. }
  4909. };
  4910. Tools.UnregisterTopRootEvents = function (events) {
  4911. for (var index = 0; index < events.length; index++) {
  4912. var event = events[index];
  4913. window.removeEventListener(event.name, event.handler);
  4914. try {
  4915. if (window.parent) {
  4916. window.parent.removeEventListener(event.name, event.handler);
  4917. }
  4918. }
  4919. catch (e) {
  4920. }
  4921. }
  4922. };
  4923. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4924. // Read the contents of the framebuffer
  4925. var numberOfChannelsByLine = width * 4;
  4926. var halfHeight = height / 2;
  4927. //Reading datas from WebGL
  4928. var data = engine.readPixels(0, 0, width, height);
  4929. //To flip image on Y axis.
  4930. for (var i = 0; i < halfHeight; i++) {
  4931. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4932. var currentCell = j + i * numberOfChannelsByLine;
  4933. var targetLine = height - i - 1;
  4934. var targetCell = j + targetLine * numberOfChannelsByLine;
  4935. var temp = data[currentCell];
  4936. data[currentCell] = data[targetCell];
  4937. data[targetCell] = temp;
  4938. }
  4939. }
  4940. // Create a 2D canvas to store the result
  4941. if (!screenshotCanvas) {
  4942. screenshotCanvas = document.createElement('canvas');
  4943. }
  4944. screenshotCanvas.width = width;
  4945. screenshotCanvas.height = height;
  4946. var context = screenshotCanvas.getContext('2d');
  4947. // Copy the pixels to a 2D canvas
  4948. var imageData = context.createImageData(width, height);
  4949. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4950. var castData = imageData.data;
  4951. castData.set(data);
  4952. context.putImageData(imageData, 0, 0);
  4953. var base64Image = screenshotCanvas.toDataURL();
  4954. if (successCallback) {
  4955. successCallback(base64Image);
  4956. }
  4957. else {
  4958. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4959. if (("download" in document.createElement("a"))) {
  4960. var a = window.document.createElement("a");
  4961. a.href = base64Image;
  4962. var date = new Date();
  4963. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4964. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4965. window.document.body.appendChild(a);
  4966. a.addEventListener("click", function () {
  4967. a.parentElement.removeChild(a);
  4968. });
  4969. a.click();
  4970. }
  4971. else {
  4972. var newWindow = window.open("");
  4973. var img = newWindow.document.createElement("img");
  4974. img.src = base64Image;
  4975. newWindow.document.body.appendChild(img);
  4976. }
  4977. }
  4978. };
  4979. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4980. var width;
  4981. var height;
  4982. //If a precision value is specified
  4983. if (size.precision) {
  4984. width = Math.round(engine.getRenderWidth() * size.precision);
  4985. height = Math.round(width / engine.getAspectRatio(camera));
  4986. size = { width: width, height: height };
  4987. }
  4988. else if (size.width && size.height) {
  4989. width = size.width;
  4990. height = size.height;
  4991. }
  4992. else if (size.width && !size.height) {
  4993. width = size.width;
  4994. height = Math.round(width / engine.getAspectRatio(camera));
  4995. size = { width: width, height: height };
  4996. }
  4997. else if (size.height && !size.width) {
  4998. height = size.height;
  4999. width = Math.round(height * engine.getAspectRatio(camera));
  5000. size = { width: width, height: height };
  5001. }
  5002. else if (!isNaN(size)) {
  5003. height = size;
  5004. width = size;
  5005. }
  5006. else {
  5007. Tools.Error("Invalid 'size' parameter !");
  5008. return;
  5009. }
  5010. var scene = camera.getScene();
  5011. var previousCamera = null;
  5012. if (scene.activeCamera !== camera) {
  5013. previousCamera = scene.activeCamera;
  5014. scene.activeCamera = camera;
  5015. }
  5016. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5017. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5018. texture.renderList = scene.meshes;
  5019. texture.onAfterRenderObservable.add(function () {
  5020. Tools.DumpFramebuffer(width, height, engine, successCallback);
  5021. });
  5022. scene.incrementRenderId();
  5023. scene.resetCachedMaterial();
  5024. texture.render(true);
  5025. texture.dispose();
  5026. if (previousCamera) {
  5027. scene.activeCamera = previousCamera;
  5028. }
  5029. camera.getProjectionMatrix(true); // Force cache refresh;
  5030. };
  5031. // XHR response validator for local file scenario
  5032. Tools.ValidateXHRData = function (xhr, dataType) {
  5033. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5034. if (dataType === void 0) { dataType = 7; }
  5035. try {
  5036. if (dataType & 1) {
  5037. if (xhr.responseText && xhr.responseText.length > 0) {
  5038. return true;
  5039. }
  5040. else if (dataType === 1) {
  5041. return false;
  5042. }
  5043. }
  5044. if (dataType & 2) {
  5045. // Check header width and height since there is no "TGA" magic number
  5046. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5047. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5048. return true;
  5049. }
  5050. else if (dataType === 2) {
  5051. return false;
  5052. }
  5053. }
  5054. if (dataType & 4) {
  5055. // Check for the "DDS" magic number
  5056. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5057. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5058. return true;
  5059. }
  5060. else {
  5061. return false;
  5062. }
  5063. }
  5064. }
  5065. catch (e) {
  5066. }
  5067. return false;
  5068. };
  5069. Object.defineProperty(Tools, "NoneLogLevel", {
  5070. get: function () {
  5071. return Tools._NoneLogLevel;
  5072. },
  5073. enumerable: true,
  5074. configurable: true
  5075. });
  5076. Object.defineProperty(Tools, "MessageLogLevel", {
  5077. get: function () {
  5078. return Tools._MessageLogLevel;
  5079. },
  5080. enumerable: true,
  5081. configurable: true
  5082. });
  5083. Object.defineProperty(Tools, "WarningLogLevel", {
  5084. get: function () {
  5085. return Tools._WarningLogLevel;
  5086. },
  5087. enumerable: true,
  5088. configurable: true
  5089. });
  5090. Object.defineProperty(Tools, "ErrorLogLevel", {
  5091. get: function () {
  5092. return Tools._ErrorLogLevel;
  5093. },
  5094. enumerable: true,
  5095. configurable: true
  5096. });
  5097. Object.defineProperty(Tools, "AllLogLevel", {
  5098. get: function () {
  5099. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5100. },
  5101. enumerable: true,
  5102. configurable: true
  5103. });
  5104. Tools._AddLogEntry = function (entry) {
  5105. Tools._LogCache = entry + Tools._LogCache;
  5106. if (Tools.OnNewCacheEntry) {
  5107. Tools.OnNewCacheEntry(entry);
  5108. }
  5109. };
  5110. Tools._FormatMessage = function (message) {
  5111. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5112. var date = new Date();
  5113. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5114. };
  5115. Tools._LogDisabled = function (message) {
  5116. // nothing to do
  5117. };
  5118. Tools._LogEnabled = function (message) {
  5119. var formattedMessage = Tools._FormatMessage(message);
  5120. console.log("BJS - " + formattedMessage);
  5121. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5122. Tools._AddLogEntry(entry);
  5123. };
  5124. Tools._WarnDisabled = function (message) {
  5125. // nothing to do
  5126. };
  5127. Tools._WarnEnabled = function (message) {
  5128. var formattedMessage = Tools._FormatMessage(message);
  5129. console.warn("BJS - " + formattedMessage);
  5130. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5131. Tools._AddLogEntry(entry);
  5132. };
  5133. Tools._ErrorDisabled = function (message) {
  5134. // nothing to do
  5135. };
  5136. Tools._ErrorEnabled = function (message) {
  5137. Tools.errorsCount++;
  5138. var formattedMessage = Tools._FormatMessage(message);
  5139. console.error("BJS - " + formattedMessage);
  5140. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5141. Tools._AddLogEntry(entry);
  5142. };
  5143. Object.defineProperty(Tools, "LogCache", {
  5144. get: function () {
  5145. return Tools._LogCache;
  5146. },
  5147. enumerable: true,
  5148. configurable: true
  5149. });
  5150. Tools.ClearLogCache = function () {
  5151. Tools._LogCache = "";
  5152. Tools.errorsCount = 0;
  5153. };
  5154. Object.defineProperty(Tools, "LogLevels", {
  5155. set: function (level) {
  5156. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5157. Tools.Log = Tools._LogEnabled;
  5158. }
  5159. else {
  5160. Tools.Log = Tools._LogDisabled;
  5161. }
  5162. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5163. Tools.Warn = Tools._WarnEnabled;
  5164. }
  5165. else {
  5166. Tools.Warn = Tools._WarnDisabled;
  5167. }
  5168. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5169. Tools.Error = Tools._ErrorEnabled;
  5170. }
  5171. else {
  5172. Tools.Error = Tools._ErrorDisabled;
  5173. }
  5174. },
  5175. enumerable: true,
  5176. configurable: true
  5177. });
  5178. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5179. get: function () {
  5180. return Tools._PerformanceNoneLogLevel;
  5181. },
  5182. enumerable: true,
  5183. configurable: true
  5184. });
  5185. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5186. get: function () {
  5187. return Tools._PerformanceUserMarkLogLevel;
  5188. },
  5189. enumerable: true,
  5190. configurable: true
  5191. });
  5192. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5193. get: function () {
  5194. return Tools._PerformanceConsoleLogLevel;
  5195. },
  5196. enumerable: true,
  5197. configurable: true
  5198. });
  5199. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5200. set: function (level) {
  5201. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5202. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5203. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5204. return;
  5205. }
  5206. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5207. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5208. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5209. return;
  5210. }
  5211. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5212. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5213. },
  5214. enumerable: true,
  5215. configurable: true
  5216. });
  5217. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5218. };
  5219. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._StartUserMark = function (counterName, condition) {
  5222. if (condition === void 0) { condition = true; }
  5223. if (!condition || !Tools._performance.mark) {
  5224. return;
  5225. }
  5226. Tools._performance.mark(counterName + "-Begin");
  5227. };
  5228. Tools._EndUserMark = function (counterName, condition) {
  5229. if (condition === void 0) { condition = true; }
  5230. if (!condition || !Tools._performance.mark) {
  5231. return;
  5232. }
  5233. Tools._performance.mark(counterName + "-End");
  5234. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5235. };
  5236. Tools._StartPerformanceConsole = function (counterName, condition) {
  5237. if (condition === void 0) { condition = true; }
  5238. if (!condition) {
  5239. return;
  5240. }
  5241. Tools._StartUserMark(counterName, condition);
  5242. if (console.time) {
  5243. console.time(counterName);
  5244. }
  5245. };
  5246. Tools._EndPerformanceConsole = function (counterName, condition) {
  5247. if (condition === void 0) { condition = true; }
  5248. if (!condition) {
  5249. return;
  5250. }
  5251. Tools._EndUserMark(counterName, condition);
  5252. if (console.time) {
  5253. console.timeEnd(counterName);
  5254. }
  5255. };
  5256. Object.defineProperty(Tools, "Now", {
  5257. get: function () {
  5258. if (window.performance && window.performance.now) {
  5259. return window.performance.now();
  5260. }
  5261. return new Date().getTime();
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. /**
  5267. * This method will return the name of the class used to create the instance of the given object.
  5268. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5269. * @param object the object to get the class name from
  5270. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5271. */
  5272. Tools.getClassName = function (object, isType) {
  5273. if (isType === void 0) { isType = false; }
  5274. var name = null;
  5275. if (!isType && object.getClassName) {
  5276. name = object.getClassName();
  5277. }
  5278. else {
  5279. if (object instanceof Object) {
  5280. var classObj = isType ? object : Object.getPrototypeOf(object);
  5281. name = classObj.constructor["__bjsclassName__"];
  5282. }
  5283. if (!name) {
  5284. name = typeof object;
  5285. }
  5286. }
  5287. return name;
  5288. };
  5289. Tools.first = function (array, predicate) {
  5290. for (var _i = 0; _i < array.length; _i++) {
  5291. var el = array[_i];
  5292. if (predicate(el)) {
  5293. return el;
  5294. }
  5295. }
  5296. };
  5297. /**
  5298. * 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.
  5299. * @param array
  5300. */
  5301. Tools.arrayOrStringFeeder = function (array) {
  5302. return function (index) {
  5303. if (index >= array.length) {
  5304. return null;
  5305. }
  5306. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5307. if (val && val.getHashCode) {
  5308. val = val.getHashCode();
  5309. }
  5310. if (typeof val === "string") {
  5311. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5312. }
  5313. return val;
  5314. };
  5315. };
  5316. /**
  5317. * Compute the hashCode of a stream of number
  5318. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5319. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5320. * @return the hash code computed
  5321. */
  5322. Tools.hashCodeFromStream = function (feeder) {
  5323. // Based from here: http://stackoverflow.com/a/7616484/802124
  5324. var hash = 0;
  5325. var index = 0;
  5326. var chr = feeder(index++);
  5327. while (chr != null) {
  5328. hash = ((hash << 5) - hash) + chr;
  5329. hash |= 0; // Convert to 32bit integer
  5330. chr = feeder(index++);
  5331. }
  5332. return hash;
  5333. };
  5334. Tools.BaseUrl = "";
  5335. Tools.CorsBehavior = "anonymous";
  5336. Tools.UseFallbackTexture = true;
  5337. // Logs
  5338. Tools._NoneLogLevel = 0;
  5339. Tools._MessageLogLevel = 1;
  5340. Tools._WarningLogLevel = 2;
  5341. Tools._ErrorLogLevel = 4;
  5342. Tools._LogCache = "";
  5343. Tools.errorsCount = 0;
  5344. Tools.Log = Tools._LogEnabled;
  5345. Tools.Warn = Tools._WarnEnabled;
  5346. Tools.Error = Tools._ErrorEnabled;
  5347. // Performances
  5348. Tools._PerformanceNoneLogLevel = 0;
  5349. Tools._PerformanceUserMarkLogLevel = 1;
  5350. Tools._PerformanceConsoleLogLevel = 2;
  5351. Tools._performance = window.performance;
  5352. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5353. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5354. return Tools;
  5355. })();
  5356. BABYLON.Tools = Tools;
  5357. /**
  5358. * This class is used to track a performance counter which is number based.
  5359. * The user has access to many properties which give statistics of different nature
  5360. *
  5361. * The implementer can track two kinds of Performance Counter: time and count
  5362. * 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.
  5363. * 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.
  5364. */
  5365. var PerfCounter = (function () {
  5366. function PerfCounter() {
  5367. this._startMonitoringTime = 0;
  5368. this._min = 0;
  5369. this._max = 0;
  5370. this._average = 0;
  5371. this._lastSecAverage = 0;
  5372. this._current = 0;
  5373. this._totalValueCount = 0;
  5374. this._totalAccumulated = 0;
  5375. this._lastSecAccumulated = 0;
  5376. this._lastSecTime = 0;
  5377. this._lastSecValueCount = 0;
  5378. }
  5379. Object.defineProperty(PerfCounter.prototype, "min", {
  5380. /**
  5381. * Returns the smallest value ever
  5382. */
  5383. get: function () {
  5384. return this._min;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(PerfCounter.prototype, "max", {
  5390. /**
  5391. * Returns the biggest value ever
  5392. */
  5393. get: function () {
  5394. return this._max;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Object.defineProperty(PerfCounter.prototype, "average", {
  5400. /**
  5401. * Returns the average value since the performance counter is running
  5402. */
  5403. get: function () {
  5404. return this._average;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5410. /**
  5411. * Returns the average value of the last second the counter was monitored
  5412. */
  5413. get: function () {
  5414. return this._lastSecAverage;
  5415. },
  5416. enumerable: true,
  5417. configurable: true
  5418. });
  5419. Object.defineProperty(PerfCounter.prototype, "current", {
  5420. /**
  5421. * Returns the current value
  5422. */
  5423. get: function () {
  5424. return this._current;
  5425. },
  5426. enumerable: true,
  5427. configurable: true
  5428. });
  5429. /**
  5430. * Call this method to start monitoring a new frame.
  5431. * 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.
  5432. */
  5433. PerfCounter.prototype.fetchNewFrame = function () {
  5434. this._totalValueCount++;
  5435. this._current = 0;
  5436. };
  5437. /**
  5438. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5439. * @param newCount the count value to add to the monitored count
  5440. * @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.
  5441. */
  5442. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5443. this._current += newCount;
  5444. if (fetchResult) {
  5445. this._fetchResult();
  5446. }
  5447. };
  5448. /**
  5449. * Start monitoring this performance counter
  5450. */
  5451. PerfCounter.prototype.beginMonitoring = function () {
  5452. this._startMonitoringTime = Tools.Now;
  5453. };
  5454. /**
  5455. * Compute the time lapsed since the previous beginMonitoring() call.
  5456. * @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
  5457. */
  5458. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5459. if (newFrame === void 0) { newFrame = true; }
  5460. if (newFrame) {
  5461. this.fetchNewFrame();
  5462. }
  5463. var currentTime = Tools.Now;
  5464. this._current = currentTime - this._startMonitoringTime;
  5465. if (newFrame) {
  5466. this._fetchResult();
  5467. }
  5468. };
  5469. PerfCounter.prototype._fetchResult = function () {
  5470. this._totalAccumulated += this._current;
  5471. // Min/Max update
  5472. this._min = Math.min(this._min, this._current);
  5473. this._max = Math.max(this._max, this._current);
  5474. this._average = this._totalAccumulated / this._totalValueCount;
  5475. // Reset last sec?
  5476. if ((this._startMonitoringTime - this._lastSecTime) > 1000) {
  5477. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5478. this._lastSecTime = this._startMonitoringTime;
  5479. this._lastSecAccumulated = 0;
  5480. this._lastSecValueCount = 0;
  5481. }
  5482. };
  5483. return PerfCounter;
  5484. })();
  5485. BABYLON.PerfCounter = PerfCounter;
  5486. /**
  5487. * Use this className as a decorator on a given class definition to add it a name.
  5488. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5489. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5490. * @param name
  5491. */
  5492. function className(name) {
  5493. return function (target) {
  5494. target["__bjsclassName__"] = name;
  5495. };
  5496. }
  5497. BABYLON.className = className;
  5498. /**
  5499. * An implementation of a loop for asynchronous functions.
  5500. */
  5501. var AsyncLoop = (function () {
  5502. /**
  5503. * Constroctor.
  5504. * @param iterations the number of iterations.
  5505. * @param _fn the function to run each iteration
  5506. * @param _successCallback the callback that will be called upon succesful execution
  5507. * @param offset starting offset.
  5508. */
  5509. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5510. if (offset === void 0) { offset = 0; }
  5511. this.iterations = iterations;
  5512. this._fn = _fn;
  5513. this._successCallback = _successCallback;
  5514. this.index = offset - 1;
  5515. this._done = false;
  5516. }
  5517. /**
  5518. * Execute the next iteration. Must be called after the last iteration was finished.
  5519. */
  5520. AsyncLoop.prototype.executeNext = function () {
  5521. if (!this._done) {
  5522. if (this.index + 1 < this.iterations) {
  5523. ++this.index;
  5524. this._fn(this);
  5525. }
  5526. else {
  5527. this.breakLoop();
  5528. }
  5529. }
  5530. };
  5531. /**
  5532. * Break the loop and run the success callback.
  5533. */
  5534. AsyncLoop.prototype.breakLoop = function () {
  5535. this._done = true;
  5536. this._successCallback();
  5537. };
  5538. /**
  5539. * Helper function
  5540. */
  5541. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5542. if (offset === void 0) { offset = 0; }
  5543. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5544. loop.executeNext();
  5545. return loop;
  5546. };
  5547. /**
  5548. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5549. * @param iterations total number of iterations
  5550. * @param syncedIterations number of synchronous iterations in each async iteration.
  5551. * @param fn the function to call each iteration.
  5552. * @param callback a success call back that will be called when iterating stops.
  5553. * @param breakFunction a break condition (optional)
  5554. * @param timeout timeout settings for the setTimeout function. default - 0.
  5555. * @constructor
  5556. */
  5557. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5558. if (timeout === void 0) { timeout = 0; }
  5559. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5560. if (breakFunction && breakFunction())
  5561. loop.breakLoop();
  5562. else {
  5563. setTimeout(function () {
  5564. for (var i = 0; i < syncedIterations; ++i) {
  5565. var iteration = (loop.index * syncedIterations) + i;
  5566. if (iteration >= iterations)
  5567. break;
  5568. fn(iteration);
  5569. if (breakFunction && breakFunction()) {
  5570. loop.breakLoop();
  5571. break;
  5572. }
  5573. }
  5574. loop.executeNext();
  5575. }, timeout);
  5576. }
  5577. }, callback);
  5578. };
  5579. return AsyncLoop;
  5580. })();
  5581. BABYLON.AsyncLoop = AsyncLoop;
  5582. })(BABYLON || (BABYLON = {}));
  5583. var BABYLON;
  5584. (function (BABYLON) {
  5585. var Internals;
  5586. (function (Internals) {
  5587. var _AlphaState = (function () {
  5588. function _AlphaState() {
  5589. this._isAlphaBlendDirty = false;
  5590. this._isBlendFunctionParametersDirty = false;
  5591. this._alphaBlend = false;
  5592. this._blendFunctionParameters = new Array(4);
  5593. }
  5594. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5595. get: function () {
  5596. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5602. get: function () {
  5603. return this._alphaBlend;
  5604. },
  5605. set: function (value) {
  5606. if (this._alphaBlend === value) {
  5607. return;
  5608. }
  5609. this._alphaBlend = value;
  5610. this._isAlphaBlendDirty = true;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5616. if (this._blendFunctionParameters[0] === value0 &&
  5617. this._blendFunctionParameters[1] === value1 &&
  5618. this._blendFunctionParameters[2] === value2 &&
  5619. this._blendFunctionParameters[3] === value3) {
  5620. return;
  5621. }
  5622. this._blendFunctionParameters[0] = value0;
  5623. this._blendFunctionParameters[1] = value1;
  5624. this._blendFunctionParameters[2] = value2;
  5625. this._blendFunctionParameters[3] = value3;
  5626. this._isBlendFunctionParametersDirty = true;
  5627. };
  5628. _AlphaState.prototype.reset = function () {
  5629. this._alphaBlend = false;
  5630. this._blendFunctionParameters[0] = null;
  5631. this._blendFunctionParameters[1] = null;
  5632. this._blendFunctionParameters[2] = null;
  5633. this._blendFunctionParameters[3] = null;
  5634. this._isAlphaBlendDirty = true;
  5635. this._isBlendFunctionParametersDirty = false;
  5636. };
  5637. _AlphaState.prototype.apply = function (gl) {
  5638. if (!this.isDirty) {
  5639. return;
  5640. }
  5641. // Alpha blend
  5642. if (this._isAlphaBlendDirty) {
  5643. if (this._alphaBlend) {
  5644. gl.enable(gl.BLEND);
  5645. }
  5646. else {
  5647. gl.disable(gl.BLEND);
  5648. }
  5649. this._isAlphaBlendDirty = false;
  5650. }
  5651. // Alpha function
  5652. if (this._isBlendFunctionParametersDirty) {
  5653. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5654. this._isBlendFunctionParametersDirty = false;
  5655. }
  5656. };
  5657. return _AlphaState;
  5658. })();
  5659. Internals._AlphaState = _AlphaState;
  5660. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5661. })(BABYLON || (BABYLON = {}));
  5662. var BABYLON;
  5663. (function (BABYLON) {
  5664. var Internals;
  5665. (function (Internals) {
  5666. var _DepthCullingState = (function () {
  5667. function _DepthCullingState() {
  5668. this._isDepthTestDirty = false;
  5669. this._isDepthMaskDirty = false;
  5670. this._isDepthFuncDirty = false;
  5671. this._isCullFaceDirty = false;
  5672. this._isCullDirty = false;
  5673. this._isZOffsetDirty = false;
  5674. }
  5675. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5676. get: function () {
  5677. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5678. },
  5679. enumerable: true,
  5680. configurable: true
  5681. });
  5682. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5683. get: function () {
  5684. return this._zOffset;
  5685. },
  5686. set: function (value) {
  5687. if (this._zOffset === value) {
  5688. return;
  5689. }
  5690. this._zOffset = value;
  5691. this._isZOffsetDirty = true;
  5692. },
  5693. enumerable: true,
  5694. configurable: true
  5695. });
  5696. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5697. get: function () {
  5698. return this._cullFace;
  5699. },
  5700. set: function (value) {
  5701. if (this._cullFace === value) {
  5702. return;
  5703. }
  5704. this._cullFace = value;
  5705. this._isCullFaceDirty = true;
  5706. },
  5707. enumerable: true,
  5708. configurable: true
  5709. });
  5710. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5711. get: function () {
  5712. return this._cull;
  5713. },
  5714. set: function (value) {
  5715. if (this._cull === value) {
  5716. return;
  5717. }
  5718. this._cull = value;
  5719. this._isCullDirty = true;
  5720. },
  5721. enumerable: true,
  5722. configurable: true
  5723. });
  5724. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5725. get: function () {
  5726. return this._depthFunc;
  5727. },
  5728. set: function (value) {
  5729. if (this._depthFunc === value) {
  5730. return;
  5731. }
  5732. this._depthFunc = value;
  5733. this._isDepthFuncDirty = true;
  5734. },
  5735. enumerable: true,
  5736. configurable: true
  5737. });
  5738. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5739. get: function () {
  5740. return this._depthMask;
  5741. },
  5742. set: function (value) {
  5743. if (this._depthMask === value) {
  5744. return;
  5745. }
  5746. this._depthMask = value;
  5747. this._isDepthMaskDirty = true;
  5748. },
  5749. enumerable: true,
  5750. configurable: true
  5751. });
  5752. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5753. get: function () {
  5754. return this._depthTest;
  5755. },
  5756. set: function (value) {
  5757. if (this._depthTest === value) {
  5758. return;
  5759. }
  5760. this._depthTest = value;
  5761. this._isDepthTestDirty = true;
  5762. },
  5763. enumerable: true,
  5764. configurable: true
  5765. });
  5766. _DepthCullingState.prototype.reset = function () {
  5767. this._depthMask = true;
  5768. this._depthTest = true;
  5769. this._depthFunc = null;
  5770. this._cullFace = null;
  5771. this._cull = null;
  5772. this._zOffset = 0;
  5773. this._isDepthTestDirty = true;
  5774. this._isDepthMaskDirty = true;
  5775. this._isDepthFuncDirty = false;
  5776. this._isCullFaceDirty = false;
  5777. this._isCullDirty = false;
  5778. this._isZOffsetDirty = false;
  5779. };
  5780. _DepthCullingState.prototype.apply = function (gl) {
  5781. if (!this.isDirty) {
  5782. return;
  5783. }
  5784. // Cull
  5785. if (this._isCullDirty) {
  5786. if (this.cull) {
  5787. gl.enable(gl.CULL_FACE);
  5788. }
  5789. else {
  5790. gl.disable(gl.CULL_FACE);
  5791. }
  5792. this._isCullDirty = false;
  5793. }
  5794. // Cull face
  5795. if (this._isCullFaceDirty) {
  5796. gl.cullFace(this.cullFace);
  5797. this._isCullFaceDirty = false;
  5798. }
  5799. // Depth mask
  5800. if (this._isDepthMaskDirty) {
  5801. gl.depthMask(this.depthMask);
  5802. this._isDepthMaskDirty = false;
  5803. }
  5804. // Depth test
  5805. if (this._isDepthTestDirty) {
  5806. if (this.depthTest) {
  5807. gl.enable(gl.DEPTH_TEST);
  5808. }
  5809. else {
  5810. gl.disable(gl.DEPTH_TEST);
  5811. }
  5812. this._isDepthTestDirty = false;
  5813. }
  5814. // Depth func
  5815. if (this._isDepthFuncDirty) {
  5816. gl.depthFunc(this.depthFunc);
  5817. this._isDepthFuncDirty = false;
  5818. }
  5819. // zOffset
  5820. if (this._isZOffsetDirty) {
  5821. if (this.zOffset) {
  5822. gl.enable(gl.POLYGON_OFFSET_FILL);
  5823. gl.polygonOffset(this.zOffset, 0);
  5824. }
  5825. else {
  5826. gl.disable(gl.POLYGON_OFFSET_FILL);
  5827. }
  5828. this._isZOffsetDirty = false;
  5829. }
  5830. };
  5831. return _DepthCullingState;
  5832. })();
  5833. Internals._DepthCullingState = _DepthCullingState;
  5834. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5835. })(BABYLON || (BABYLON = {}));
  5836. var BABYLON;
  5837. (function (BABYLON) {
  5838. var compileShader = function (gl, source, type, defines) {
  5839. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5840. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5841. gl.compileShader(shader);
  5842. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5843. throw new Error(gl.getShaderInfoLog(shader));
  5844. }
  5845. return shader;
  5846. };
  5847. var getWebGLTextureType = function (gl, type) {
  5848. var textureType = gl.UNSIGNED_BYTE;
  5849. if (type === Engine.TEXTURETYPE_FLOAT)
  5850. textureType = gl.FLOAT;
  5851. return textureType;
  5852. };
  5853. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5854. var magFilter = gl.NEAREST;
  5855. var minFilter = gl.NEAREST;
  5856. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5857. magFilter = gl.LINEAR;
  5858. if (generateMipMaps) {
  5859. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5860. }
  5861. else {
  5862. minFilter = gl.LINEAR;
  5863. }
  5864. }
  5865. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5866. magFilter = gl.LINEAR;
  5867. if (generateMipMaps) {
  5868. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5869. }
  5870. else {
  5871. minFilter = gl.LINEAR;
  5872. }
  5873. }
  5874. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5875. magFilter = gl.NEAREST;
  5876. if (generateMipMaps) {
  5877. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5878. }
  5879. else {
  5880. minFilter = gl.NEAREST;
  5881. }
  5882. }
  5883. return {
  5884. min: minFilter,
  5885. mag: magFilter
  5886. };
  5887. };
  5888. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5890. var engine = scene.getEngine();
  5891. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5892. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5893. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5894. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5895. texture._baseWidth = width;
  5896. texture._baseHeight = height;
  5897. texture._width = potWidth;
  5898. texture._height = potHeight;
  5899. texture.isReady = true;
  5900. processFunction(potWidth, potHeight);
  5901. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5904. if (!noMipmap && !isCompressed) {
  5905. gl.generateMipmap(gl.TEXTURE_2D);
  5906. }
  5907. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5908. engine.resetTextureCache();
  5909. scene._removePendingData(texture);
  5910. if (onLoad) {
  5911. onLoad();
  5912. }
  5913. };
  5914. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5915. var img;
  5916. var onload = function () {
  5917. loadedImages[index] = img;
  5918. loadedImages._internalCount++;
  5919. scene._removePendingData(img);
  5920. if (loadedImages._internalCount === 6) {
  5921. onfinish(loadedImages);
  5922. }
  5923. };
  5924. var onerror = function () {
  5925. scene._removePendingData(img);
  5926. };
  5927. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5928. scene._addPendingData(img);
  5929. };
  5930. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5931. var loadedImages = [];
  5932. loadedImages._internalCount = 0;
  5933. for (var index = 0; index < 6; index++) {
  5934. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5935. }
  5936. };
  5937. var InstancingAttributeInfo = (function () {
  5938. function InstancingAttributeInfo() {
  5939. }
  5940. return InstancingAttributeInfo;
  5941. })();
  5942. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5943. var EngineCapabilities = (function () {
  5944. function EngineCapabilities() {
  5945. }
  5946. return EngineCapabilities;
  5947. })();
  5948. BABYLON.EngineCapabilities = EngineCapabilities;
  5949. /**
  5950. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5951. */
  5952. var Engine = (function () {
  5953. /**
  5954. * @constructor
  5955. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5956. * @param {boolean} [antialias] - enable antialias
  5957. * @param options - further options to be sent to the getContext function
  5958. */
  5959. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5960. var _this = this;
  5961. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5962. // Public members
  5963. this.isFullscreen = false;
  5964. this.isPointerLock = false;
  5965. this.cullBackFaces = true;
  5966. this.renderEvenInBackground = true;
  5967. // To enable/disable IDB support and avoid XHR on .manifest
  5968. this.enableOfflineSupport = true;
  5969. this.scenes = new Array();
  5970. this._windowIsBackground = false;
  5971. this._webGLVersion = "1.0";
  5972. this._drawCalls = new BABYLON.PerfCounter();
  5973. this._renderingQueueLaunched = false;
  5974. this._activeRenderLoops = [];
  5975. // FPS
  5976. this.fpsRange = 60;
  5977. this.previousFramesDuration = [];
  5978. this.fps = 60;
  5979. this.deltaTime = 0;
  5980. // States
  5981. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5982. this._alphaState = new BABYLON.Internals._AlphaState();
  5983. this._alphaMode = Engine.ALPHA_DISABLE;
  5984. // Cache
  5985. this._loadedTexturesCache = new Array();
  5986. this._maxTextureChannels = 16;
  5987. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5988. this._compiledEffects = {};
  5989. this._uintIndicesCurrentlySet = false;
  5990. this._currentBoundBuffer = new Array();
  5991. this._currentBufferPointers = [];
  5992. this._currentInstanceLocations = new Array();
  5993. this._currentInstanceBuffers = new Array();
  5994. this._renderingCanvas = canvas;
  5995. this._externalData = new BABYLON.StringDictionary();
  5996. options = options || {};
  5997. options.antialias = antialias;
  5998. if (options.preserveDrawingBuffer === undefined) {
  5999. options.preserveDrawingBuffer = false;
  6000. }
  6001. // GL
  6002. //try {
  6003. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6004. // if (this._gl) {
  6005. // this._webGLVersion = "2.0";
  6006. // }
  6007. //} catch (e) {
  6008. // // Do nothing
  6009. //}
  6010. if (!this._gl) {
  6011. try {
  6012. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6013. }
  6014. catch (e) {
  6015. throw new Error("WebGL not supported");
  6016. }
  6017. }
  6018. if (!this._gl) {
  6019. throw new Error("WebGL not supported");
  6020. }
  6021. this._onBlur = function () {
  6022. _this._windowIsBackground = true;
  6023. };
  6024. this._onFocus = function () {
  6025. _this._windowIsBackground = false;
  6026. };
  6027. window.addEventListener("blur", this._onBlur);
  6028. window.addEventListener("focus", this._onFocus);
  6029. // Viewport
  6030. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6031. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6032. this.resize();
  6033. // Caps
  6034. this._caps = new EngineCapabilities();
  6035. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6036. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6037. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6038. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6039. // Infos
  6040. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6041. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6042. if (rendererInfo != null) {
  6043. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6044. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6045. }
  6046. if (!this._glVendor) {
  6047. this._glVendor = "Unknown vendor";
  6048. }
  6049. if (!this._glRenderer) {
  6050. this._glRenderer = "Unknown renderer";
  6051. }
  6052. // Extensions
  6053. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6054. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6055. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6056. 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');
  6057. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6058. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6059. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6060. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6061. this._caps.highPrecisionShaderSupported = true;
  6062. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6063. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6064. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6065. if (this._gl.getShaderPrecisionFormat) {
  6066. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6067. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6068. }
  6069. // Depth buffer
  6070. this.setDepthBuffer(true);
  6071. this.setDepthFunctionToLessOrEqual();
  6072. this.setDepthWrite(true);
  6073. // Fullscreen
  6074. this._onFullscreenChange = function () {
  6075. if (document.fullscreen !== undefined) {
  6076. _this.isFullscreen = document.fullscreen;
  6077. }
  6078. else if (document.mozFullScreen !== undefined) {
  6079. _this.isFullscreen = document.mozFullScreen;
  6080. }
  6081. else if (document.webkitIsFullScreen !== undefined) {
  6082. _this.isFullscreen = document.webkitIsFullScreen;
  6083. }
  6084. else if (document.msIsFullScreen !== undefined) {
  6085. _this.isFullscreen = document.msIsFullScreen;
  6086. }
  6087. // Pointer lock
  6088. if (_this.isFullscreen && _this._pointerLockRequested) {
  6089. canvas.requestPointerLock = canvas.requestPointerLock ||
  6090. canvas.msRequestPointerLock ||
  6091. canvas.mozRequestPointerLock ||
  6092. canvas.webkitRequestPointerLock;
  6093. if (canvas.requestPointerLock) {
  6094. canvas.requestPointerLock();
  6095. }
  6096. }
  6097. };
  6098. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6099. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6100. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6101. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6102. // Pointer lock
  6103. this._onPointerLockChange = function () {
  6104. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6105. document.webkitPointerLockElement === canvas ||
  6106. document.msPointerLockElement === canvas ||
  6107. document.pointerLockElement === canvas);
  6108. };
  6109. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6110. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6111. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6112. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6113. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6114. Engine.audioEngine = new BABYLON.AudioEngine();
  6115. }
  6116. //default loading screen
  6117. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6118. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6119. }
  6120. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6121. get: function () {
  6122. return Engine._ALPHA_DISABLE;
  6123. },
  6124. enumerable: true,
  6125. configurable: true
  6126. });
  6127. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6128. get: function () {
  6129. return Engine._ALPHA_ONEONE;
  6130. },
  6131. enumerable: true,
  6132. configurable: true
  6133. });
  6134. Object.defineProperty(Engine, "ALPHA_ADD", {
  6135. get: function () {
  6136. return Engine._ALPHA_ADD;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6142. get: function () {
  6143. return Engine._ALPHA_COMBINE;
  6144. },
  6145. enumerable: true,
  6146. configurable: true
  6147. });
  6148. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6149. get: function () {
  6150. return Engine._ALPHA_SUBTRACT;
  6151. },
  6152. enumerable: true,
  6153. configurable: true
  6154. });
  6155. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6156. get: function () {
  6157. return Engine._ALPHA_MULTIPLY;
  6158. },
  6159. enumerable: true,
  6160. configurable: true
  6161. });
  6162. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6163. get: function () {
  6164. return Engine._ALPHA_MAXIMIZED;
  6165. },
  6166. enumerable: true,
  6167. configurable: true
  6168. });
  6169. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6170. get: function () {
  6171. return Engine._DELAYLOADSTATE_NONE;
  6172. },
  6173. enumerable: true,
  6174. configurable: true
  6175. });
  6176. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6177. get: function () {
  6178. return Engine._DELAYLOADSTATE_LOADED;
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6184. get: function () {
  6185. return Engine._DELAYLOADSTATE_LOADING;
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6191. get: function () {
  6192. return Engine._DELAYLOADSTATE_NOTLOADED;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6198. get: function () {
  6199. return Engine._TEXTUREFORMAT_ALPHA;
  6200. },
  6201. enumerable: true,
  6202. configurable: true
  6203. });
  6204. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6205. get: function () {
  6206. return Engine._TEXTUREFORMAT_LUMINANCE;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6212. get: function () {
  6213. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6214. },
  6215. enumerable: true,
  6216. configurable: true
  6217. });
  6218. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6219. get: function () {
  6220. return Engine._TEXTUREFORMAT_RGB;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6226. get: function () {
  6227. return Engine._TEXTUREFORMAT_RGBA;
  6228. },
  6229. enumerable: true,
  6230. configurable: true
  6231. });
  6232. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6233. get: function () {
  6234. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6240. get: function () {
  6241. return Engine._TEXTURETYPE_FLOAT;
  6242. },
  6243. enumerable: true,
  6244. configurable: true
  6245. });
  6246. Object.defineProperty(Engine, "Version", {
  6247. get: function () {
  6248. return "2.5-alpha";
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6254. get: function () {
  6255. return this._webGLVersion;
  6256. },
  6257. enumerable: true,
  6258. configurable: true
  6259. });
  6260. Engine.prototype._prepareWorkingCanvas = function () {
  6261. if (this._workingCanvas) {
  6262. return;
  6263. }
  6264. this._workingCanvas = document.createElement("canvas");
  6265. this._workingContext = this._workingCanvas.getContext("2d");
  6266. };
  6267. Engine.prototype.resetTextureCache = function () {
  6268. for (var index = 0; index < this._maxTextureChannels; index++) {
  6269. this._activeTexturesCache[index] = null;
  6270. }
  6271. };
  6272. Engine.prototype.getGlInfo = function () {
  6273. return {
  6274. vendor: this._glVendor,
  6275. renderer: this._glRenderer,
  6276. version: this._glVersion
  6277. };
  6278. };
  6279. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6280. if (useScreen === void 0) { useScreen = false; }
  6281. var viewport = camera.viewport;
  6282. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6283. };
  6284. Engine.prototype.getRenderWidth = function (useScreen) {
  6285. if (useScreen === void 0) { useScreen = false; }
  6286. if (!useScreen && this._currentRenderTarget) {
  6287. return this._currentRenderTarget._width;
  6288. }
  6289. return this._renderingCanvas.width;
  6290. };
  6291. Engine.prototype.getRenderHeight = function (useScreen) {
  6292. if (useScreen === void 0) { useScreen = false; }
  6293. if (!useScreen && this._currentRenderTarget) {
  6294. return this._currentRenderTarget._height;
  6295. }
  6296. return this._renderingCanvas.height;
  6297. };
  6298. Engine.prototype.getRenderingCanvas = function () {
  6299. return this._renderingCanvas;
  6300. };
  6301. Engine.prototype.getRenderingCanvasClientRect = function () {
  6302. return this._renderingCanvas.getBoundingClientRect();
  6303. };
  6304. Engine.prototype.setHardwareScalingLevel = function (level) {
  6305. this._hardwareScalingLevel = level;
  6306. this.resize();
  6307. };
  6308. Engine.prototype.getHardwareScalingLevel = function () {
  6309. return this._hardwareScalingLevel;
  6310. };
  6311. Engine.prototype.getLoadedTexturesCache = function () {
  6312. return this._loadedTexturesCache;
  6313. };
  6314. Engine.prototype.getCaps = function () {
  6315. return this._caps;
  6316. };
  6317. Object.defineProperty(Engine.prototype, "drawCalls", {
  6318. get: function () {
  6319. return this._drawCalls.current;
  6320. },
  6321. enumerable: true,
  6322. configurable: true
  6323. });
  6324. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6325. get: function () {
  6326. return this._drawCalls;
  6327. },
  6328. enumerable: true,
  6329. configurable: true
  6330. });
  6331. Engine.prototype.getDepthFunction = function () {
  6332. return this._depthCullingState.depthFunc;
  6333. };
  6334. Engine.prototype.setDepthFunction = function (depthFunc) {
  6335. this._depthCullingState.depthFunc = depthFunc;
  6336. };
  6337. Engine.prototype.setDepthFunctionToGreater = function () {
  6338. this._depthCullingState.depthFunc = this._gl.GREATER;
  6339. };
  6340. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6341. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6342. };
  6343. Engine.prototype.setDepthFunctionToLess = function () {
  6344. this._depthCullingState.depthFunc = this._gl.LESS;
  6345. };
  6346. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6347. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6348. };
  6349. /**
  6350. * stop executing a render loop function and remove it from the execution array
  6351. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6352. */
  6353. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6354. if (!renderFunction) {
  6355. this._activeRenderLoops = [];
  6356. return;
  6357. }
  6358. var index = this._activeRenderLoops.indexOf(renderFunction);
  6359. if (index >= 0) {
  6360. this._activeRenderLoops.splice(index, 1);
  6361. }
  6362. };
  6363. Engine.prototype._renderLoop = function () {
  6364. var shouldRender = true;
  6365. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6366. shouldRender = false;
  6367. }
  6368. if (shouldRender) {
  6369. // Start new frame
  6370. this.beginFrame();
  6371. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6372. var renderFunction = this._activeRenderLoops[index];
  6373. renderFunction();
  6374. }
  6375. // Present
  6376. this.endFrame();
  6377. }
  6378. if (this._activeRenderLoops.length > 0) {
  6379. // Register new frame
  6380. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6381. }
  6382. else {
  6383. this._renderingQueueLaunched = false;
  6384. }
  6385. };
  6386. /**
  6387. * Register and execute a render loop. The engine can have more than one render function.
  6388. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6389. * @example
  6390. * engine.runRenderLoop(function () {
  6391. * scene.render()
  6392. * })
  6393. */
  6394. Engine.prototype.runRenderLoop = function (renderFunction) {
  6395. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6396. return;
  6397. }
  6398. this._activeRenderLoops.push(renderFunction);
  6399. if (!this._renderingQueueLaunched) {
  6400. this._renderingQueueLaunched = true;
  6401. this._bindedRenderFunction = this._renderLoop.bind(this);
  6402. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6403. }
  6404. };
  6405. /**
  6406. * Toggle full screen mode.
  6407. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6408. * @param {any} options - an options object to be sent to the requestFullscreen function
  6409. */
  6410. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6411. if (this.isFullscreen) {
  6412. BABYLON.Tools.ExitFullscreen();
  6413. }
  6414. else {
  6415. this._pointerLockRequested = requestPointerLock;
  6416. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6417. }
  6418. };
  6419. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6420. this.applyStates();
  6421. if (backBuffer) {
  6422. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6423. }
  6424. if (depthStencil && this._depthCullingState.depthMask) {
  6425. this._gl.clearDepth(1.0);
  6426. }
  6427. var mode = 0;
  6428. if (backBuffer) {
  6429. mode |= this._gl.COLOR_BUFFER_BIT;
  6430. }
  6431. if (depthStencil && this._depthCullingState.depthMask) {
  6432. mode |= this._gl.DEPTH_BUFFER_BIT;
  6433. }
  6434. this._gl.clear(mode);
  6435. };
  6436. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6437. var gl = this._gl;
  6438. // Save state
  6439. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6440. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6441. // Change state
  6442. gl.enable(gl.SCISSOR_TEST);
  6443. gl.scissor(x, y, width, height);
  6444. // Clear
  6445. this.clear(clearColor, true, true);
  6446. // Restore state
  6447. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6448. if (curScissor === true) {
  6449. gl.enable(gl.SCISSOR_TEST);
  6450. }
  6451. else {
  6452. gl.disable(gl.SCISSOR_TEST);
  6453. }
  6454. };
  6455. /**
  6456. * Set the WebGL's viewport
  6457. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6458. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6459. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6460. */
  6461. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6462. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6463. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6464. var x = viewport.x || 0;
  6465. var y = viewport.y || 0;
  6466. this._cachedViewport = viewport;
  6467. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6468. };
  6469. /**
  6470. * Directly set the WebGL Viewport
  6471. * The x, y, width & height are directly passed to the WebGL call
  6472. * @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.
  6473. */
  6474. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6475. var currentViewport = this._cachedViewport;
  6476. this._cachedViewport = null;
  6477. this._gl.viewport(x, y, width, height);
  6478. return currentViewport;
  6479. };
  6480. Engine.prototype.beginFrame = function () {
  6481. this._measureFps();
  6482. };
  6483. Engine.prototype.endFrame = function () {
  6484. //this.flushFramebuffer();
  6485. };
  6486. /**
  6487. * resize the view according to the canvas' size.
  6488. * @example
  6489. * window.addEventListener("resize", function () {
  6490. * engine.resize();
  6491. * });
  6492. */
  6493. Engine.prototype.resize = function () {
  6494. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6495. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6496. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6497. for (var index = 0; index < this.scenes.length; index++) {
  6498. var scene = this.scenes[index];
  6499. if (scene.debugLayer.isVisible()) {
  6500. scene.debugLayer._syncPositions();
  6501. }
  6502. }
  6503. };
  6504. /**
  6505. * force a specific size of the canvas
  6506. * @param {number} width - the new canvas' width
  6507. * @param {number} height - the new canvas' height
  6508. */
  6509. Engine.prototype.setSize = function (width, height) {
  6510. this._renderingCanvas.width = width;
  6511. this._renderingCanvas.height = height;
  6512. for (var index = 0; index < this.scenes.length; index++) {
  6513. var scene = this.scenes[index];
  6514. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6515. var cam = scene.cameras[camIndex];
  6516. cam._currentRenderId = 0;
  6517. }
  6518. }
  6519. };
  6520. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6521. this._currentRenderTarget = texture;
  6522. var gl = this._gl;
  6523. this.bindUnboundFramebuffer(texture._framebuffer);
  6524. if (texture.isCube) {
  6525. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6526. }
  6527. else {
  6528. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6529. }
  6530. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6531. this.wipeCaches();
  6532. };
  6533. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6534. if (this._currentFramebuffer !== framebuffer) {
  6535. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6536. this._currentFramebuffer = framebuffer;
  6537. }
  6538. };
  6539. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6540. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6541. this._currentRenderTarget = null;
  6542. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6543. var gl = this._gl;
  6544. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6545. gl.generateMipmap(gl.TEXTURE_2D);
  6546. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6547. }
  6548. this.bindUnboundFramebuffer(null);
  6549. };
  6550. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6551. if (texture.generateMipMaps) {
  6552. var gl = this._gl;
  6553. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6554. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6555. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6556. }
  6557. };
  6558. Engine.prototype.flushFramebuffer = function () {
  6559. this._gl.flush();
  6560. };
  6561. Engine.prototype.restoreDefaultFramebuffer = function () {
  6562. this._currentRenderTarget = null;
  6563. this.bindUnboundFramebuffer(null);
  6564. this.setViewport(this._cachedViewport);
  6565. this.wipeCaches();
  6566. };
  6567. // VBOs
  6568. Engine.prototype._resetVertexBufferBinding = function () {
  6569. this.bindArrayBuffer(null);
  6570. this._cachedVertexBuffers = null;
  6571. };
  6572. Engine.prototype.createVertexBuffer = function (vertices) {
  6573. var vbo = this._gl.createBuffer();
  6574. this.bindArrayBuffer(vbo);
  6575. if (vertices instanceof Float32Array) {
  6576. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6577. }
  6578. else {
  6579. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6580. }
  6581. this._resetVertexBufferBinding();
  6582. vbo.references = 1;
  6583. return vbo;
  6584. };
  6585. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6586. var vbo = this._gl.createBuffer();
  6587. this.bindArrayBuffer(vbo);
  6588. if (vertices instanceof Float32Array) {
  6589. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6590. }
  6591. else {
  6592. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6593. }
  6594. this._resetVertexBufferBinding();
  6595. vbo.references = 1;
  6596. return vbo;
  6597. };
  6598. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6599. this.bindArrayBuffer(vertexBuffer);
  6600. if (offset === undefined) {
  6601. offset = 0;
  6602. }
  6603. if (count === undefined) {
  6604. if (vertices instanceof Float32Array) {
  6605. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6606. }
  6607. else {
  6608. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6609. }
  6610. }
  6611. else {
  6612. if (vertices instanceof Float32Array) {
  6613. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6614. }
  6615. else {
  6616. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6617. }
  6618. }
  6619. this._resetVertexBufferBinding();
  6620. };
  6621. Engine.prototype._resetIndexBufferBinding = function () {
  6622. this.bindIndexBuffer(null);
  6623. this._cachedIndexBuffer = null;
  6624. };
  6625. Engine.prototype.createIndexBuffer = function (indices) {
  6626. var vbo = this._gl.createBuffer();
  6627. this.bindIndexBuffer(vbo);
  6628. // Check for 32 bits indices
  6629. var arrayBuffer;
  6630. var need32Bits = false;
  6631. if (this._caps.uintIndices) {
  6632. for (var index = 0; index < indices.length; index++) {
  6633. if (indices[index] > 65535) {
  6634. need32Bits = true;
  6635. break;
  6636. }
  6637. }
  6638. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6639. }
  6640. else {
  6641. arrayBuffer = new Uint16Array(indices);
  6642. }
  6643. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6644. this._resetIndexBufferBinding();
  6645. vbo.references = 1;
  6646. vbo.is32Bits = need32Bits;
  6647. return vbo;
  6648. };
  6649. Engine.prototype.bindArrayBuffer = function (buffer) {
  6650. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6651. };
  6652. Engine.prototype.bindIndexBuffer = function (buffer) {
  6653. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6654. };
  6655. Engine.prototype.bindBuffer = function (buffer, target) {
  6656. if (this._currentBoundBuffer[target] !== buffer) {
  6657. this._gl.bindBuffer(target, buffer);
  6658. this._currentBoundBuffer[target] = buffer;
  6659. }
  6660. };
  6661. Engine.prototype.updateArrayBuffer = function (data) {
  6662. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6663. };
  6664. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6665. var pointer = this._currentBufferPointers[indx];
  6666. var changed = false;
  6667. if (!pointer) {
  6668. changed = true;
  6669. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6670. }
  6671. else {
  6672. if (pointer.buffer !== buffer) {
  6673. pointer.buffer = buffer;
  6674. changed = true;
  6675. }
  6676. if (pointer.size !== size) {
  6677. pointer.size = size;
  6678. changed = true;
  6679. }
  6680. if (pointer.type !== type) {
  6681. pointer.type = type;
  6682. changed = true;
  6683. }
  6684. if (pointer.normalized !== normalized) {
  6685. pointer.normalized = normalized;
  6686. changed = true;
  6687. }
  6688. if (pointer.stride !== stride) {
  6689. pointer.stride = stride;
  6690. changed = true;
  6691. }
  6692. if (pointer.offset !== offset) {
  6693. pointer.offset = offset;
  6694. changed = true;
  6695. }
  6696. }
  6697. if (changed) {
  6698. this.bindArrayBuffer(buffer);
  6699. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6700. }
  6701. };
  6702. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6703. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6704. this._cachedVertexBuffers = vertexBuffer;
  6705. this._cachedEffectForVertexBuffers = effect;
  6706. var offset = 0;
  6707. for (var index = 0; index < vertexDeclaration.length; index++) {
  6708. var order = effect.getAttributeLocation(index);
  6709. if (order >= 0) {
  6710. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6711. }
  6712. offset += vertexDeclaration[index] * 4;
  6713. }
  6714. }
  6715. if (this._cachedIndexBuffer !== indexBuffer) {
  6716. this._cachedIndexBuffer = indexBuffer;
  6717. this.bindIndexBuffer(indexBuffer);
  6718. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6719. }
  6720. };
  6721. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6722. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6723. this._cachedVertexBuffers = vertexBuffers;
  6724. this._cachedEffectForVertexBuffers = effect;
  6725. var attributes = effect.getAttributesNames();
  6726. for (var index = 0; index < attributes.length; index++) {
  6727. var order = effect.getAttributeLocation(index);
  6728. if (order >= 0) {
  6729. var vertexBuffer = vertexBuffers[attributes[index]];
  6730. if (!vertexBuffer) {
  6731. continue;
  6732. }
  6733. var buffer = vertexBuffer.getBuffer();
  6734. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6735. if (vertexBuffer.getIsInstanced()) {
  6736. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6737. this._currentInstanceLocations.push(order);
  6738. this._currentInstanceBuffers.push(buffer);
  6739. }
  6740. }
  6741. }
  6742. }
  6743. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6744. this._cachedIndexBuffer = indexBuffer;
  6745. this.bindIndexBuffer(indexBuffer);
  6746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6747. }
  6748. };
  6749. Engine.prototype.unbindInstanceAttributes = function () {
  6750. var boundBuffer;
  6751. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6752. var instancesBuffer = this._currentInstanceBuffers[i];
  6753. if (boundBuffer != instancesBuffer) {
  6754. boundBuffer = instancesBuffer;
  6755. this.bindArrayBuffer(instancesBuffer);
  6756. }
  6757. var offsetLocation = this._currentInstanceLocations[i];
  6758. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6759. }
  6760. this._currentInstanceBuffers.length = 0;
  6761. this._currentInstanceLocations.length = 0;
  6762. };
  6763. Engine.prototype._releaseBuffer = function (buffer) {
  6764. buffer.references--;
  6765. if (buffer.references === 0) {
  6766. this._gl.deleteBuffer(buffer);
  6767. return true;
  6768. }
  6769. return false;
  6770. };
  6771. Engine.prototype.createInstancesBuffer = function (capacity) {
  6772. var buffer = this._gl.createBuffer();
  6773. buffer.capacity = capacity;
  6774. this.bindArrayBuffer(buffer);
  6775. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6776. return buffer;
  6777. };
  6778. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6779. this._gl.deleteBuffer(buffer);
  6780. };
  6781. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6782. this.bindArrayBuffer(instancesBuffer);
  6783. if (data) {
  6784. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6785. }
  6786. if (offsetLocations[0].index !== undefined) {
  6787. var stride = 0;
  6788. for (var i = 0; i < offsetLocations.length; i++) {
  6789. var ai = offsetLocations[i];
  6790. stride += ai.attributeSize * 4;
  6791. }
  6792. for (var i = 0; i < offsetLocations.length; i++) {
  6793. var ai = offsetLocations[i];
  6794. this._gl.enableVertexAttribArray(ai.index);
  6795. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6796. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6797. this._currentInstanceLocations.push(ai.index);
  6798. this._currentInstanceBuffers.push(instancesBuffer);
  6799. }
  6800. }
  6801. else {
  6802. for (var index = 0; index < 4; index++) {
  6803. var offsetLocation = offsetLocations[index];
  6804. this._gl.enableVertexAttribArray(offsetLocation);
  6805. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6806. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6807. this._currentInstanceLocations.push(offsetLocation);
  6808. this._currentInstanceBuffers.push(instancesBuffer);
  6809. }
  6810. }
  6811. };
  6812. Engine.prototype.applyStates = function () {
  6813. this._depthCullingState.apply(this._gl);
  6814. this._alphaState.apply(this._gl);
  6815. };
  6816. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6817. // Apply states
  6818. this.applyStates();
  6819. this._drawCalls.addCount(1, false);
  6820. // Render
  6821. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6822. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6823. if (instancesCount) {
  6824. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6825. return;
  6826. }
  6827. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6828. };
  6829. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6830. // Apply states
  6831. this.applyStates();
  6832. this._drawCalls.addCount(1, false);
  6833. if (instancesCount) {
  6834. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6835. return;
  6836. }
  6837. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6838. };
  6839. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6840. // Apply states
  6841. this.applyStates();
  6842. this._drawCalls.addCount(1, false);
  6843. if (instancesCount) {
  6844. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6845. return;
  6846. }
  6847. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6848. };
  6849. // Shaders
  6850. Engine.prototype._releaseEffect = function (effect) {
  6851. if (this._compiledEffects[effect._key]) {
  6852. delete this._compiledEffects[effect._key];
  6853. if (effect.getProgram()) {
  6854. this._gl.deleteProgram(effect.getProgram());
  6855. }
  6856. }
  6857. };
  6858. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6859. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6860. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6861. var name = vertex + "+" + fragment + "@" + defines;
  6862. if (this._compiledEffects[name]) {
  6863. return this._compiledEffects[name];
  6864. }
  6865. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6866. effect._key = name;
  6867. this._compiledEffects[name] = effect;
  6868. return effect;
  6869. };
  6870. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6871. if (uniformsNames === void 0) { uniformsNames = []; }
  6872. if (samplers === void 0) { samplers = []; }
  6873. if (defines === void 0) { defines = ""; }
  6874. return this.createEffect({
  6875. vertex: "particles",
  6876. fragmentElement: fragmentName
  6877. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6878. };
  6879. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6880. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6881. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6882. var shaderProgram = this._gl.createProgram();
  6883. this._gl.attachShader(shaderProgram, vertexShader);
  6884. this._gl.attachShader(shaderProgram, fragmentShader);
  6885. this._gl.linkProgram(shaderProgram);
  6886. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6887. if (!linked) {
  6888. var error = this._gl.getProgramInfoLog(shaderProgram);
  6889. if (error) {
  6890. throw new Error(error);
  6891. }
  6892. }
  6893. this._gl.deleteShader(vertexShader);
  6894. this._gl.deleteShader(fragmentShader);
  6895. return shaderProgram;
  6896. };
  6897. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6898. var results = [];
  6899. for (var index = 0; index < uniformsNames.length; index++) {
  6900. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6901. }
  6902. return results;
  6903. };
  6904. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6905. var results = [];
  6906. for (var index = 0; index < attributesNames.length; index++) {
  6907. try {
  6908. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6909. }
  6910. catch (e) {
  6911. results.push(-1);
  6912. }
  6913. }
  6914. return results;
  6915. };
  6916. Engine.prototype.enableEffect = function (effect) {
  6917. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6918. if (effect && effect.onBind) {
  6919. effect.onBind(effect);
  6920. }
  6921. return;
  6922. }
  6923. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6924. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6925. // Use program
  6926. this.setProgram(effect.getProgram());
  6927. var i, ul;
  6928. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6929. this._vertexAttribArraysToUse[i] = false;
  6930. }
  6931. var attributesCount = effect.getAttributesCount();
  6932. for (i = 0; i < attributesCount; i++) {
  6933. // Attributes
  6934. var order = effect.getAttributeLocation(i);
  6935. if (order >= 0) {
  6936. this._vertexAttribArraysToUse[order] = true;
  6937. }
  6938. }
  6939. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6940. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6941. continue;
  6942. }
  6943. this._vertexAttribArraysEnabled[i] = false;
  6944. this._gl.disableVertexAttribArray(i);
  6945. }
  6946. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6947. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6948. this._vertexAttribArraysEnabled[i] = true;
  6949. this._gl.enableVertexAttribArray(i);
  6950. }
  6951. }
  6952. this._currentEffect = effect;
  6953. if (effect.onBind) {
  6954. effect.onBind(effect);
  6955. }
  6956. };
  6957. Engine.prototype.setArray = function (uniform, array) {
  6958. if (!uniform)
  6959. return;
  6960. this._gl.uniform1fv(uniform, array);
  6961. };
  6962. Engine.prototype.setArray2 = function (uniform, array) {
  6963. if (!uniform || array.length % 2 !== 0)
  6964. return;
  6965. this._gl.uniform2fv(uniform, array);
  6966. };
  6967. Engine.prototype.setArray3 = function (uniform, array) {
  6968. if (!uniform || array.length % 3 !== 0)
  6969. return;
  6970. this._gl.uniform3fv(uniform, array);
  6971. };
  6972. Engine.prototype.setArray4 = function (uniform, array) {
  6973. if (!uniform || array.length % 4 !== 0)
  6974. return;
  6975. this._gl.uniform4fv(uniform, array);
  6976. };
  6977. Engine.prototype.setMatrices = function (uniform, matrices) {
  6978. if (!uniform)
  6979. return;
  6980. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6981. };
  6982. Engine.prototype.setMatrix = function (uniform, matrix) {
  6983. if (!uniform)
  6984. return;
  6985. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6986. };
  6987. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6988. if (!uniform)
  6989. return;
  6990. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6991. };
  6992. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6993. if (!uniform)
  6994. return;
  6995. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6996. };
  6997. Engine.prototype.setFloat = function (uniform, value) {
  6998. if (!uniform)
  6999. return;
  7000. this._gl.uniform1f(uniform, value);
  7001. };
  7002. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7003. if (!uniform)
  7004. return;
  7005. this._gl.uniform2f(uniform, x, y);
  7006. };
  7007. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7008. if (!uniform)
  7009. return;
  7010. this._gl.uniform3f(uniform, x, y, z);
  7011. };
  7012. Engine.prototype.setBool = function (uniform, bool) {
  7013. if (!uniform)
  7014. return;
  7015. this._gl.uniform1i(uniform, bool);
  7016. };
  7017. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7018. if (!uniform)
  7019. return;
  7020. this._gl.uniform4f(uniform, x, y, z, w);
  7021. };
  7022. Engine.prototype.setColor3 = function (uniform, color3) {
  7023. if (!uniform)
  7024. return;
  7025. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7026. };
  7027. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7028. if (!uniform)
  7029. return;
  7030. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7031. };
  7032. // States
  7033. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7034. if (zOffset === void 0) { zOffset = 0; }
  7035. if (reverseSide === void 0) { reverseSide = false; }
  7036. // Culling
  7037. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7038. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7039. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7040. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7041. if (culling) {
  7042. this._depthCullingState.cullFace = cullFace;
  7043. this._depthCullingState.cull = true;
  7044. }
  7045. else {
  7046. this._depthCullingState.cull = false;
  7047. }
  7048. }
  7049. // Z offset
  7050. this._depthCullingState.zOffset = zOffset;
  7051. };
  7052. Engine.prototype.setDepthBuffer = function (enable) {
  7053. this._depthCullingState.depthTest = enable;
  7054. };
  7055. Engine.prototype.getDepthWrite = function () {
  7056. return this._depthCullingState.depthMask;
  7057. };
  7058. Engine.prototype.setDepthWrite = function (enable) {
  7059. this._depthCullingState.depthMask = enable;
  7060. };
  7061. Engine.prototype.setColorWrite = function (enable) {
  7062. this._gl.colorMask(enable, enable, enable, enable);
  7063. };
  7064. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7065. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7066. if (this._alphaMode === mode) {
  7067. return;
  7068. }
  7069. switch (mode) {
  7070. case Engine.ALPHA_DISABLE:
  7071. this._alphaState.alphaBlend = false;
  7072. break;
  7073. case Engine.ALPHA_COMBINE:
  7074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7075. this._alphaState.alphaBlend = true;
  7076. break;
  7077. case Engine.ALPHA_ONEONE:
  7078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7079. this._alphaState.alphaBlend = true;
  7080. break;
  7081. case Engine.ALPHA_ADD:
  7082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7083. this._alphaState.alphaBlend = true;
  7084. break;
  7085. case Engine.ALPHA_SUBTRACT:
  7086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7087. this._alphaState.alphaBlend = true;
  7088. break;
  7089. case Engine.ALPHA_MULTIPLY:
  7090. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7091. this._alphaState.alphaBlend = true;
  7092. break;
  7093. case Engine.ALPHA_MAXIMIZED:
  7094. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7095. this._alphaState.alphaBlend = true;
  7096. break;
  7097. }
  7098. if (!noDepthWriteChange) {
  7099. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7100. }
  7101. this._alphaMode = mode;
  7102. };
  7103. Engine.prototype.getAlphaMode = function () {
  7104. return this._alphaMode;
  7105. };
  7106. Engine.prototype.setAlphaTesting = function (enable) {
  7107. this._alphaTest = enable;
  7108. };
  7109. Engine.prototype.getAlphaTesting = function () {
  7110. return this._alphaTest;
  7111. };
  7112. // Textures
  7113. Engine.prototype.wipeCaches = function () {
  7114. this.resetTextureCache();
  7115. this._currentEffect = null;
  7116. this._depthCullingState.reset();
  7117. this.setDepthFunctionToLessOrEqual();
  7118. this._alphaState.reset();
  7119. this._cachedVertexBuffers = null;
  7120. this._cachedIndexBuffer = null;
  7121. this._cachedEffectForVertexBuffers = null;
  7122. };
  7123. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7124. var gl = this._gl;
  7125. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7126. var magFilter = gl.NEAREST;
  7127. var minFilter = gl.NEAREST;
  7128. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7129. magFilter = gl.LINEAR;
  7130. minFilter = gl.LINEAR;
  7131. }
  7132. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7133. magFilter = gl.LINEAR;
  7134. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7135. }
  7136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7138. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7139. texture.samplingMode = samplingMode;
  7140. };
  7141. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7142. var _this = this;
  7143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7144. if (onLoad === void 0) { onLoad = null; }
  7145. if (onError === void 0) { onError = null; }
  7146. if (buffer === void 0) { buffer = null; }
  7147. var texture = this._gl.createTexture();
  7148. var extension;
  7149. var fromData = false;
  7150. if (url.substr(0, 5) === "data:") {
  7151. fromData = true;
  7152. }
  7153. if (!fromData)
  7154. extension = url.substr(url.length - 4, 4).toLowerCase();
  7155. else {
  7156. var oldUrl = url;
  7157. fromData = oldUrl.split(':');
  7158. url = oldUrl;
  7159. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7160. }
  7161. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7162. var isTGA = (extension === ".tga");
  7163. scene._addPendingData(texture);
  7164. texture.url = url;
  7165. texture.noMipmap = noMipmap;
  7166. texture.references = 1;
  7167. texture.samplingMode = samplingMode;
  7168. this._loadedTexturesCache.push(texture);
  7169. var onerror = function () {
  7170. scene._removePendingData(texture);
  7171. if (onError) {
  7172. onError();
  7173. }
  7174. };
  7175. var callback;
  7176. if (isTGA) {
  7177. callback = function (arrayBuffer) {
  7178. var data = new Uint8Array(arrayBuffer);
  7179. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7180. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7181. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7182. }, onLoad, samplingMode);
  7183. };
  7184. if (!(fromData instanceof Array))
  7185. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7186. callback(arrayBuffer);
  7187. }, onerror, scene.database, true);
  7188. else
  7189. callback(buffer);
  7190. }
  7191. else if (isDDS) {
  7192. callback = function (data) {
  7193. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7194. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7195. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7196. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7197. }, onLoad, samplingMode);
  7198. };
  7199. if (!(fromData instanceof Array))
  7200. BABYLON.Tools.LoadFile(url, function (data) {
  7201. callback(data);
  7202. }, onerror, scene.database, true);
  7203. else
  7204. callback(buffer);
  7205. }
  7206. else {
  7207. var onload = function (img) {
  7208. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7209. var isPot = (img.width === potWidth && img.height === potHeight);
  7210. if (!isPot) {
  7211. _this._prepareWorkingCanvas();
  7212. _this._workingCanvas.width = potWidth;
  7213. _this._workingCanvas.height = potHeight;
  7214. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7215. _this._workingContext.imageSmoothingEnabled = false;
  7216. _this._workingContext.mozImageSmoothingEnabled = false;
  7217. _this._workingContext.oImageSmoothingEnabled = false;
  7218. _this._workingContext.webkitImageSmoothingEnabled = false;
  7219. _this._workingContext.msImageSmoothingEnabled = false;
  7220. }
  7221. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7222. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7223. _this._workingContext.imageSmoothingEnabled = true;
  7224. _this._workingContext.mozImageSmoothingEnabled = true;
  7225. _this._workingContext.oImageSmoothingEnabled = true;
  7226. _this._workingContext.webkitImageSmoothingEnabled = true;
  7227. _this._workingContext.msImageSmoothingEnabled = true;
  7228. }
  7229. }
  7230. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7231. }, onLoad, samplingMode);
  7232. };
  7233. if (!(fromData instanceof Array))
  7234. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7235. else
  7236. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7237. }
  7238. return texture;
  7239. };
  7240. Engine.prototype._getInternalFormat = function (format) {
  7241. var internalFormat = this._gl.RGBA;
  7242. switch (format) {
  7243. case Engine.TEXTUREFORMAT_ALPHA:
  7244. internalFormat = this._gl.ALPHA;
  7245. break;
  7246. case Engine.TEXTUREFORMAT_LUMINANCE:
  7247. internalFormat = this._gl.LUMINANCE;
  7248. break;
  7249. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7250. internalFormat = this._gl.LUMINANCE_ALPHA;
  7251. break;
  7252. case Engine.TEXTUREFORMAT_RGB:
  7253. internalFormat = this._gl.RGB;
  7254. break;
  7255. case Engine.TEXTUREFORMAT_RGBA:
  7256. internalFormat = this._gl.RGBA;
  7257. break;
  7258. }
  7259. return internalFormat;
  7260. };
  7261. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7262. if (compression === void 0) { compression = null; }
  7263. var internalFormat = this._getInternalFormat(format);
  7264. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7265. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7266. if (texture._width % 4 !== 0) {
  7267. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7268. }
  7269. if (compression) {
  7270. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7271. }
  7272. else {
  7273. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7274. }
  7275. if (texture.generateMipMaps) {
  7276. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7277. }
  7278. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7279. this.resetTextureCache();
  7280. texture.isReady = true;
  7281. };
  7282. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7283. if (compression === void 0) { compression = null; }
  7284. var texture = this._gl.createTexture();
  7285. texture._baseWidth = width;
  7286. texture._baseHeight = height;
  7287. texture._width = width;
  7288. texture._height = height;
  7289. texture.references = 1;
  7290. this.updateRawTexture(texture, data, format, invertY, compression);
  7291. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7292. // Filters
  7293. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7295. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7296. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7297. texture.samplingMode = samplingMode;
  7298. this._loadedTexturesCache.push(texture);
  7299. return texture;
  7300. };
  7301. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7302. var texture = this._gl.createTexture();
  7303. texture._baseWidth = width;
  7304. texture._baseHeight = height;
  7305. if (generateMipMaps) {
  7306. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7307. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7308. }
  7309. this.resetTextureCache();
  7310. texture._width = width;
  7311. texture._height = height;
  7312. texture.isReady = false;
  7313. texture.generateMipMaps = generateMipMaps;
  7314. texture.references = 1;
  7315. texture.samplingMode = samplingMode;
  7316. this.updateTextureSamplingMode(samplingMode, texture);
  7317. this._loadedTexturesCache.push(texture);
  7318. return texture;
  7319. };
  7320. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7321. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7322. if (texture.isCube) {
  7323. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7324. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7325. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7326. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7327. }
  7328. else {
  7329. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7333. }
  7334. };
  7335. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7336. if (premulAlpha === void 0) { premulAlpha = false; }
  7337. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7338. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7339. if (premulAlpha) {
  7340. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7341. }
  7342. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7343. if (texture.generateMipMaps) {
  7344. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7345. }
  7346. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7347. this.resetTextureCache();
  7348. texture.isReady = true;
  7349. };
  7350. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7351. if (texture._isDisabled) {
  7352. return;
  7353. }
  7354. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7355. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7356. try {
  7357. // Testing video texture support
  7358. if (this._videoTextureSupported === undefined) {
  7359. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7360. if (this._gl.getError() !== 0) {
  7361. this._videoTextureSupported = false;
  7362. }
  7363. else {
  7364. this._videoTextureSupported = true;
  7365. }
  7366. }
  7367. // Copy video through the current working canvas if video texture is not supported
  7368. if (!this._videoTextureSupported) {
  7369. if (!texture._workingCanvas) {
  7370. texture._workingCanvas = document.createElement("canvas");
  7371. texture._workingContext = texture._workingCanvas.getContext("2d");
  7372. texture._workingCanvas.width = texture._width;
  7373. texture._workingCanvas.height = texture._height;
  7374. }
  7375. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7376. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7377. }
  7378. else {
  7379. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7380. }
  7381. if (texture.generateMipMaps) {
  7382. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7383. }
  7384. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7385. this.resetTextureCache();
  7386. texture.isReady = true;
  7387. }
  7388. catch (ex) {
  7389. // Something unexpected
  7390. // Let's disable the texture
  7391. texture._isDisabled = true;
  7392. }
  7393. };
  7394. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7395. // old version had a "generateMipMaps" arg instead of options.
  7396. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7397. // in the same way, generateDepthBuffer is defaulted to true
  7398. var generateMipMaps = false;
  7399. var generateDepthBuffer = true;
  7400. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7401. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7402. if (options !== undefined) {
  7403. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7404. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7405. type = options.type === undefined ? type : options.type;
  7406. if (options.samplingMode !== undefined) {
  7407. samplingMode = options.samplingMode;
  7408. }
  7409. if (type === Engine.TEXTURETYPE_FLOAT) {
  7410. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7411. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7412. }
  7413. }
  7414. var gl = this._gl;
  7415. var texture = gl.createTexture();
  7416. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7417. var width = size.width || size;
  7418. var height = size.height || size;
  7419. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7420. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7421. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7422. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7423. }
  7424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7428. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7429. var depthBuffer;
  7430. // Create the depth buffer
  7431. if (generateDepthBuffer) {
  7432. depthBuffer = gl.createRenderbuffer();
  7433. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7434. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7435. }
  7436. // Create the framebuffer
  7437. var framebuffer = gl.createFramebuffer();
  7438. this.bindUnboundFramebuffer(framebuffer);
  7439. if (generateDepthBuffer) {
  7440. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7441. }
  7442. if (generateMipMaps) {
  7443. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7444. }
  7445. // Unbind
  7446. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7447. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7448. this.bindUnboundFramebuffer(null);
  7449. texture._framebuffer = framebuffer;
  7450. if (generateDepthBuffer) {
  7451. texture._depthBuffer = depthBuffer;
  7452. }
  7453. texture._baseWidth = width;
  7454. texture._baseHeight = height;
  7455. texture._width = width;
  7456. texture._height = height;
  7457. texture.isReady = true;
  7458. texture.generateMipMaps = generateMipMaps;
  7459. texture.references = 1;
  7460. texture.samplingMode = samplingMode;
  7461. this.resetTextureCache();
  7462. this._loadedTexturesCache.push(texture);
  7463. return texture;
  7464. };
  7465. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7466. var gl = this._gl;
  7467. var texture = gl.createTexture();
  7468. var generateMipMaps = true;
  7469. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7470. if (options !== undefined) {
  7471. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7472. if (options.samplingMode !== undefined) {
  7473. samplingMode = options.samplingMode;
  7474. }
  7475. }
  7476. texture.isCube = true;
  7477. texture.references = 1;
  7478. texture.generateMipMaps = generateMipMaps;
  7479. texture.references = 1;
  7480. texture.samplingMode = samplingMode;
  7481. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7482. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7483. for (var face = 0; face < 6; face++) {
  7484. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7485. }
  7486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7490. // Create the depth buffer
  7491. var depthBuffer = gl.createRenderbuffer();
  7492. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7493. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7494. // Create the framebuffer
  7495. var framebuffer = gl.createFramebuffer();
  7496. this.bindUnboundFramebuffer(framebuffer);
  7497. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7498. // Mipmaps
  7499. if (texture.generateMipMaps) {
  7500. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7501. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7502. }
  7503. // Unbind
  7504. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7505. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7506. this.bindUnboundFramebuffer(null);
  7507. texture._framebuffer = framebuffer;
  7508. texture._depthBuffer = depthBuffer;
  7509. this.resetTextureCache();
  7510. texture._width = size;
  7511. texture._height = size;
  7512. texture.isReady = true;
  7513. return texture;
  7514. };
  7515. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7516. var _this = this;
  7517. var gl = this._gl;
  7518. var texture = gl.createTexture();
  7519. texture.isCube = true;
  7520. texture.url = rootUrl;
  7521. texture.references = 1;
  7522. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7523. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7524. if (isDDS) {
  7525. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7526. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7527. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7528. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7530. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7531. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7533. }
  7534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7538. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7539. _this.resetTextureCache();
  7540. texture._width = info.width;
  7541. texture._height = info.height;
  7542. texture.isReady = true;
  7543. }, null, null, true);
  7544. }
  7545. else {
  7546. cascadeLoad(rootUrl, scene, function (imgs) {
  7547. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7548. var height = width;
  7549. _this._prepareWorkingCanvas();
  7550. _this._workingCanvas.width = width;
  7551. _this._workingCanvas.height = height;
  7552. var faces = [
  7553. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7554. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7555. ];
  7556. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7557. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7558. for (var index = 0; index < faces.length; index++) {
  7559. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7560. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7561. }
  7562. if (!noMipmap) {
  7563. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7564. }
  7565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7569. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7570. _this.resetTextureCache();
  7571. texture._width = width;
  7572. texture._height = height;
  7573. texture.isReady = true;
  7574. }, files);
  7575. }
  7576. return texture;
  7577. };
  7578. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7579. texture._width = width;
  7580. texture._height = height;
  7581. texture._size = width * height;
  7582. texture._baseWidth = width;
  7583. texture._baseHeight = height;
  7584. };
  7585. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7586. var _this = this;
  7587. var gl = this._gl;
  7588. var texture = gl.createTexture();
  7589. scene._addPendingData(texture);
  7590. texture.isCube = true;
  7591. texture.references = 1;
  7592. texture.url = url;
  7593. var internalFormat = this._getInternalFormat(format);
  7594. var textureType = gl.UNSIGNED_BYTE;
  7595. if (type === Engine.TEXTURETYPE_FLOAT) {
  7596. textureType = gl.FLOAT;
  7597. }
  7598. var width = size;
  7599. var height = width;
  7600. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7601. texture._width = width;
  7602. texture._height = height;
  7603. var onerror = function () {
  7604. scene._removePendingData(texture);
  7605. };
  7606. var internalCallback = function (data) {
  7607. var rgbeDataArrays = callback(data);
  7608. var facesIndex = [
  7609. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7610. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7611. ];
  7612. width = texture._width;
  7613. height = texture._height;
  7614. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7615. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7617. if (!noMipmap && isPot) {
  7618. if (mipmmapGenerator) {
  7619. var arrayTemp = [];
  7620. // Data are known to be in +X +Y +Z -X -Y -Z
  7621. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7622. arrayTemp.push(rgbeDataArrays[0]); // +X
  7623. arrayTemp.push(rgbeDataArrays[3]); // -X
  7624. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7625. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7626. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7627. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7628. var mipData = mipmmapGenerator(arrayTemp);
  7629. for (var level = 0; level < mipData.length; level++) {
  7630. var mipSize = width >> level;
  7631. // mipData is order in +X -X +Y -Y +Z -Z
  7632. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7633. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7634. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7635. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7636. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7637. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7638. }
  7639. }
  7640. else {
  7641. // Data are known to be in +X +Y +Z -X -Y -Z
  7642. for (var index = 0; index < facesIndex.length; index++) {
  7643. var faceData = rgbeDataArrays[index];
  7644. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7645. }
  7646. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7647. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7648. // By following the webgl standard changes from Revision 7, 2014/11/24
  7649. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7650. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7651. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7652. // Data are known to be in +X +Y +Z -X -Y -Z
  7653. for (var index = 0; index < facesIndex.length; index++) {
  7654. var faceData = rgbeDataArrays[index];
  7655. // Create a new RGBA Face.
  7656. var newFaceData = new Float32Array(width * height * 4);
  7657. for (var x = 0; x < width; x++) {
  7658. for (var y = 0; y < height; y++) {
  7659. var index_1 = (y * width + x) * 3;
  7660. var newIndex = (y * width + x) * 4;
  7661. // Map Old Value to new value.
  7662. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7663. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7664. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7665. // Add fully opaque alpha channel.
  7666. newFaceData[newIndex + 3] = 1;
  7667. }
  7668. }
  7669. // Reupload the face.
  7670. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7671. }
  7672. // Try to generate mipmap again.
  7673. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7674. }
  7675. }
  7676. }
  7677. else {
  7678. noMipmap = true;
  7679. }
  7680. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7683. }
  7684. else {
  7685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7687. }
  7688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7691. texture.isReady = true;
  7692. _this.resetTextureCache();
  7693. scene._removePendingData(texture);
  7694. };
  7695. BABYLON.Tools.LoadFile(url, function (data) {
  7696. internalCallback(data);
  7697. }, onerror, scene.database, true);
  7698. return texture;
  7699. };
  7700. ;
  7701. Engine.prototype._releaseTexture = function (texture) {
  7702. var gl = this._gl;
  7703. if (texture._framebuffer) {
  7704. gl.deleteFramebuffer(texture._framebuffer);
  7705. }
  7706. if (texture._depthBuffer) {
  7707. gl.deleteRenderbuffer(texture._depthBuffer);
  7708. }
  7709. gl.deleteTexture(texture);
  7710. // Unbind channels
  7711. this.unbindAllTextures();
  7712. var index = this._loadedTexturesCache.indexOf(texture);
  7713. if (index !== -1) {
  7714. this._loadedTexturesCache.splice(index, 1);
  7715. }
  7716. };
  7717. Engine.prototype.setProgram = function (program) {
  7718. if (this._currentProgram !== program) {
  7719. this._gl.useProgram(program);
  7720. this._currentProgram = program;
  7721. }
  7722. };
  7723. Engine.prototype.bindSamplers = function (effect) {
  7724. this.setProgram(effect.getProgram());
  7725. var samplers = effect.getSamplers();
  7726. for (var index = 0; index < samplers.length; index++) {
  7727. var uniform = effect.getUniform(samplers[index]);
  7728. this._gl.uniform1i(uniform, index);
  7729. }
  7730. this._currentEffect = null;
  7731. };
  7732. Engine.prototype.activateTexture = function (texture) {
  7733. if (this._activeTexture !== texture) {
  7734. this._gl.activeTexture(texture);
  7735. this._activeTexture = texture;
  7736. }
  7737. };
  7738. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7739. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7740. this._gl.bindTexture(target, texture);
  7741. this._activeTexturesCache[this._activeTexture] = texture;
  7742. }
  7743. };
  7744. Engine.prototype._bindTexture = function (channel, texture) {
  7745. if (channel < 0) {
  7746. return;
  7747. }
  7748. this.activateTexture(this._gl["TEXTURE" + channel]);
  7749. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7750. };
  7751. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7752. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7753. };
  7754. Engine.prototype.unbindAllTextures = function () {
  7755. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7756. this.activateTexture(this._gl["TEXTURE" + channel]);
  7757. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7759. }
  7760. };
  7761. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7762. if (channel < 0) {
  7763. return;
  7764. }
  7765. this._gl.uniform1i(uniform, channel);
  7766. this._setTexture(channel, texture);
  7767. };
  7768. Engine.prototype._setTexture = function (channel, texture) {
  7769. // Not ready?
  7770. if (!texture || !texture.isReady()) {
  7771. if (this._activeTexturesCache[channel] != null) {
  7772. this.activateTexture(this._gl["TEXTURE" + channel]);
  7773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7774. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7775. }
  7776. return;
  7777. }
  7778. // Video
  7779. var alreadyActivated = false;
  7780. if (texture instanceof BABYLON.VideoTexture) {
  7781. this.activateTexture(this._gl["TEXTURE" + channel]);
  7782. alreadyActivated = true;
  7783. texture.update();
  7784. }
  7785. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7786. texture.delayLoad();
  7787. return;
  7788. }
  7789. var internalTexture = texture.getInternalTexture();
  7790. if (this._activeTexturesCache[channel] === internalTexture) {
  7791. return;
  7792. }
  7793. if (!alreadyActivated) {
  7794. this.activateTexture(this._gl["TEXTURE" + channel]);
  7795. }
  7796. if (internalTexture.isCube) {
  7797. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7798. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7799. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7800. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7801. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7802. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7803. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7804. }
  7805. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7806. }
  7807. else {
  7808. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7809. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7810. internalTexture._cachedWrapU = texture.wrapU;
  7811. switch (texture.wrapU) {
  7812. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7813. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7814. break;
  7815. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7817. break;
  7818. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7820. break;
  7821. }
  7822. }
  7823. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7824. internalTexture._cachedWrapV = texture.wrapV;
  7825. switch (texture.wrapV) {
  7826. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7828. break;
  7829. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7831. break;
  7832. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7833. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7834. break;
  7835. }
  7836. }
  7837. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7838. }
  7839. };
  7840. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7841. if (channel < 0) {
  7842. return;
  7843. }
  7844. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7845. this._textureUnits = new Int32Array(textures.length);
  7846. }
  7847. for (var i = 0; i < textures.length; i++) {
  7848. this._textureUnits[i] = channel + i;
  7849. }
  7850. this._gl.uniform1iv(uniform, this._textureUnits);
  7851. for (var index = 0; index < textures.length; index++) {
  7852. this._setTexture(channel + index, textures[index]);
  7853. }
  7854. };
  7855. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7856. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7857. var value = texture.anisotropicFilteringLevel;
  7858. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7859. value = 1;
  7860. }
  7861. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7862. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7863. texture._cachedAnisotropicFilteringLevel = value;
  7864. }
  7865. };
  7866. Engine.prototype.readPixels = function (x, y, width, height) {
  7867. var data = new Uint8Array(height * width * 4);
  7868. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7869. return data;
  7870. };
  7871. /**
  7872. * Add an externaly attached data from its key.
  7873. * This method call will fail and return false, if such key already exists.
  7874. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7875. * @param key the unique key that identifies the data
  7876. * @param data the data object to associate to the key for this Engine instance
  7877. * @return true if no such key were already present and the data was added successfully, false otherwise
  7878. */
  7879. Engine.prototype.addExternalData = function (key, data) {
  7880. return this._externalData.add(key, data);
  7881. };
  7882. /**
  7883. * Get an externaly attached data from its key
  7884. * @param key the unique key that identifies the data
  7885. * @return the associated data, if present (can be null), or undefined if not present
  7886. */
  7887. Engine.prototype.getExternalData = function (key) {
  7888. return this._externalData.get(key);
  7889. };
  7890. /**
  7891. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7892. * @param key the unique key that identifies the data
  7893. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7894. * @return the associated data, can be null if the factory returned null.
  7895. */
  7896. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7897. return this._externalData.getOrAddWithFactory(key, factory);
  7898. };
  7899. /**
  7900. * Remove an externaly attached data from the Engine instance
  7901. * @param key the unique key that identifies the data
  7902. * @return true if the data was successfully removed, false if it doesn't exist
  7903. */
  7904. Engine.prototype.removeExternalData = function (key) {
  7905. return this._externalData.remove(key);
  7906. };
  7907. Engine.prototype.releaseInternalTexture = function (texture) {
  7908. if (!texture) {
  7909. return;
  7910. }
  7911. texture.references--;
  7912. // Final reference ?
  7913. if (texture.references === 0) {
  7914. var texturesCache = this.getLoadedTexturesCache();
  7915. var index = texturesCache.indexOf(texture);
  7916. if (index > -1) {
  7917. texturesCache.splice(index, 1);
  7918. }
  7919. this._releaseTexture(texture);
  7920. }
  7921. };
  7922. // Dispose
  7923. Engine.prototype.dispose = function () {
  7924. this.hideLoadingUI();
  7925. this.stopRenderLoop();
  7926. // Release scenes
  7927. while (this.scenes.length) {
  7928. this.scenes[0].dispose();
  7929. }
  7930. // Release audio engine
  7931. Engine.audioEngine.dispose();
  7932. // Release effects
  7933. for (var name in this._compiledEffects) {
  7934. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7935. }
  7936. // Unbind
  7937. if (this._vertexAttribArraysEnabled) {
  7938. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7939. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7940. continue;
  7941. }
  7942. this._gl.disableVertexAttribArray(i);
  7943. }
  7944. }
  7945. this._gl = null;
  7946. // Events
  7947. window.removeEventListener("blur", this._onBlur);
  7948. window.removeEventListener("focus", this._onFocus);
  7949. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7950. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7951. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7952. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7953. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7954. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7955. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7956. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7957. };
  7958. // Loading screen
  7959. Engine.prototype.displayLoadingUI = function () {
  7960. this._loadingScreen.displayLoadingUI();
  7961. };
  7962. Engine.prototype.hideLoadingUI = function () {
  7963. this._loadingScreen.hideLoadingUI();
  7964. };
  7965. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7966. get: function () {
  7967. return this._loadingScreen;
  7968. },
  7969. set: function (loadingScreen) {
  7970. this._loadingScreen = loadingScreen;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7976. set: function (text) {
  7977. this._loadingScreen.loadingUIText = text;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7983. set: function (color) {
  7984. this._loadingScreen.loadingUIBackgroundColor = color;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. // FPS
  7990. Engine.prototype.getFps = function () {
  7991. return this.fps;
  7992. };
  7993. Engine.prototype.getDeltaTime = function () {
  7994. return this.deltaTime;
  7995. };
  7996. Engine.prototype._measureFps = function () {
  7997. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7998. var length = this.previousFramesDuration.length;
  7999. if (length >= 2) {
  8000. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8001. }
  8002. if (length >= this.fpsRange) {
  8003. if (length > this.fpsRange) {
  8004. this.previousFramesDuration.splice(0, 1);
  8005. length = this.previousFramesDuration.length;
  8006. }
  8007. var sum = 0;
  8008. for (var id = 0; id < length - 1; id++) {
  8009. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8010. }
  8011. this.fps = 1000.0 / (sum / (length - 1));
  8012. }
  8013. };
  8014. // Statics
  8015. Engine.isSupported = function () {
  8016. try {
  8017. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8018. if (navigator.isCocoonJS) {
  8019. return true;
  8020. }
  8021. var tempcanvas = document.createElement("canvas");
  8022. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8023. return gl != null && !!window.WebGLRenderingContext;
  8024. }
  8025. catch (e) {
  8026. return false;
  8027. }
  8028. };
  8029. // Const statics
  8030. Engine._ALPHA_DISABLE = 0;
  8031. Engine._ALPHA_ADD = 1;
  8032. Engine._ALPHA_COMBINE = 2;
  8033. Engine._ALPHA_SUBTRACT = 3;
  8034. Engine._ALPHA_MULTIPLY = 4;
  8035. Engine._ALPHA_MAXIMIZED = 5;
  8036. Engine._ALPHA_ONEONE = 6;
  8037. Engine._DELAYLOADSTATE_NONE = 0;
  8038. Engine._DELAYLOADSTATE_LOADED = 1;
  8039. Engine._DELAYLOADSTATE_LOADING = 2;
  8040. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8041. Engine._TEXTUREFORMAT_ALPHA = 0;
  8042. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8043. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8044. Engine._TEXTUREFORMAT_RGB = 4;
  8045. Engine._TEXTUREFORMAT_RGBA = 5;
  8046. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8047. Engine._TEXTURETYPE_FLOAT = 1;
  8048. // Updatable statics so stick with vars here
  8049. Engine.CollisionsEpsilon = 0.001;
  8050. Engine.CodeRepository = "src/";
  8051. Engine.ShadersRepository = "src/Shaders/";
  8052. return Engine;
  8053. })();
  8054. BABYLON.Engine = Engine;
  8055. })(BABYLON || (BABYLON = {}));
  8056. var BABYLON;
  8057. (function (BABYLON) {
  8058. /**
  8059. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8060. */
  8061. var Node = (function () {
  8062. /**
  8063. * @constructor
  8064. * @param {string} name - the name and id to be given to this node
  8065. * @param {BABYLON.Scene} the scene this node will be added to
  8066. */
  8067. function Node(name, scene) {
  8068. this.state = "";
  8069. this.animations = new Array();
  8070. this._ranges = {};
  8071. this._childrenFlag = -1;
  8072. this._isEnabled = true;
  8073. this._isReady = true;
  8074. this._currentRenderId = -1;
  8075. this._parentRenderId = -1;
  8076. this.name = name;
  8077. this.id = name;
  8078. this._scene = scene;
  8079. this._initCache();
  8080. }
  8081. Object.defineProperty(Node.prototype, "parent", {
  8082. get: function () {
  8083. return this._parentNode;
  8084. },
  8085. set: function (parent) {
  8086. if (this._parentNode === parent) {
  8087. return;
  8088. }
  8089. if (this._parentNode) {
  8090. var index = this._parentNode._children.indexOf(this);
  8091. if (index !== -1) {
  8092. this._parentNode._children.splice(index, 1);
  8093. }
  8094. }
  8095. this._parentNode = parent;
  8096. if (this._parentNode) {
  8097. if (!this._parentNode._children) {
  8098. this._parentNode._children = new Array();
  8099. }
  8100. this._parentNode._children.push(this);
  8101. }
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Node.prototype.getScene = function () {
  8107. return this._scene;
  8108. };
  8109. Node.prototype.getEngine = function () {
  8110. return this._scene.getEngine();
  8111. };
  8112. // override it in derived class
  8113. Node.prototype.getWorldMatrix = function () {
  8114. return BABYLON.Matrix.Identity();
  8115. };
  8116. // override it in derived class if you add new variables to the cache
  8117. // and call the parent class method
  8118. Node.prototype._initCache = function () {
  8119. this._cache = {};
  8120. this._cache.parent = undefined;
  8121. };
  8122. Node.prototype.updateCache = function (force) {
  8123. if (!force && this.isSynchronized())
  8124. return;
  8125. this._cache.parent = this.parent;
  8126. this._updateCache();
  8127. };
  8128. // override it in derived class if you add new variables to the cache
  8129. // and call the parent class method if !ignoreParentClass
  8130. Node.prototype._updateCache = function (ignoreParentClass) {
  8131. };
  8132. // override it in derived class if you add new variables to the cache
  8133. Node.prototype._isSynchronized = function () {
  8134. return true;
  8135. };
  8136. Node.prototype._markSyncedWithParent = function () {
  8137. this._parentRenderId = this.parent._currentRenderId;
  8138. };
  8139. Node.prototype.isSynchronizedWithParent = function () {
  8140. if (!this.parent) {
  8141. return true;
  8142. }
  8143. if (this._parentRenderId !== this.parent._currentRenderId) {
  8144. return false;
  8145. }
  8146. return this.parent.isSynchronized();
  8147. };
  8148. Node.prototype.isSynchronized = function (updateCache) {
  8149. var check = this.hasNewParent();
  8150. check = check || !this.isSynchronizedWithParent();
  8151. check = check || !this._isSynchronized();
  8152. if (updateCache)
  8153. this.updateCache(true);
  8154. return !check;
  8155. };
  8156. Node.prototype.hasNewParent = function (update) {
  8157. if (this._cache.parent === this.parent)
  8158. return false;
  8159. if (update)
  8160. this._cache.parent = this.parent;
  8161. return true;
  8162. };
  8163. /**
  8164. * Is this node ready to be used/rendered
  8165. * @return {boolean} is it ready
  8166. */
  8167. Node.prototype.isReady = function () {
  8168. return this._isReady;
  8169. };
  8170. /**
  8171. * Is this node enabled.
  8172. * If the node has a parent and is enabled, the parent will be inspected as well.
  8173. * @return {boolean} whether this node (and its parent) is enabled.
  8174. * @see setEnabled
  8175. */
  8176. Node.prototype.isEnabled = function () {
  8177. if (!this._isEnabled) {
  8178. return false;
  8179. }
  8180. if (this.parent) {
  8181. return this.parent.isEnabled();
  8182. }
  8183. return true;
  8184. };
  8185. /**
  8186. * Set the enabled state of this node.
  8187. * @param {boolean} value - the new enabled state
  8188. * @see isEnabled
  8189. */
  8190. Node.prototype.setEnabled = function (value) {
  8191. this._isEnabled = value;
  8192. };
  8193. /**
  8194. * Is this node a descendant of the given node.
  8195. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8196. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8197. * @see parent
  8198. */
  8199. Node.prototype.isDescendantOf = function (ancestor) {
  8200. if (this.parent) {
  8201. if (this.parent === ancestor) {
  8202. return true;
  8203. }
  8204. return this.parent.isDescendantOf(ancestor);
  8205. }
  8206. return false;
  8207. };
  8208. /**
  8209. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8210. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8211. * @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.
  8212. * @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.
  8213. */
  8214. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8215. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8216. if (!this._children) {
  8217. return;
  8218. }
  8219. for (var index = 0; index < this._children.length; index++) {
  8220. var item = this._children[index];
  8221. if (!predicate || predicate(item)) {
  8222. results.push(item);
  8223. }
  8224. if (!directDescendantsOnly) {
  8225. item._getDescendants(results, false, predicate);
  8226. }
  8227. }
  8228. };
  8229. /**
  8230. * Will return all nodes that have this node as ascendant.
  8231. * @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.
  8232. * @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.
  8233. * @return {BABYLON.Node[]} all children nodes of all types.
  8234. */
  8235. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8236. var results = [];
  8237. this._getDescendants(results, directDescendantsOnly, predicate);
  8238. return results;
  8239. };
  8240. /**
  8241. * @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.
  8242. * @Deprecated, legacy support.
  8243. * use getDecendants instead.
  8244. */
  8245. Node.prototype.getChildren = function (predicate) {
  8246. return this.getDescendants(true, predicate);
  8247. };
  8248. /**
  8249. * Get all child-meshes of this node.
  8250. */
  8251. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8252. var results = [];
  8253. this._getDescendants(results, directDecendantsOnly, function (node) {
  8254. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8255. });
  8256. return results;
  8257. };
  8258. Node.prototype._setReady = function (state) {
  8259. if (state === this._isReady) {
  8260. return;
  8261. }
  8262. if (!state) {
  8263. this._isReady = false;
  8264. return;
  8265. }
  8266. this._isReady = true;
  8267. if (this.onReady) {
  8268. this.onReady(this);
  8269. }
  8270. };
  8271. Node.prototype.getAnimationByName = function (name) {
  8272. for (var i = 0; i < this.animations.length; i++) {
  8273. var animation = this.animations[i];
  8274. if (animation.name === name) {
  8275. return animation;
  8276. }
  8277. }
  8278. return null;
  8279. };
  8280. Node.prototype.createAnimationRange = function (name, from, to) {
  8281. // check name not already in use
  8282. if (!this._ranges[name]) {
  8283. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8284. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8285. if (this.animations[i]) {
  8286. this.animations[i].createRange(name, from, to);
  8287. }
  8288. }
  8289. }
  8290. };
  8291. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8292. if (deleteFrames === void 0) { deleteFrames = true; }
  8293. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8294. if (this.animations[i]) {
  8295. this.animations[i].deleteRange(name, deleteFrames);
  8296. }
  8297. }
  8298. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8299. };
  8300. Node.prototype.getAnimationRange = function (name) {
  8301. return this._ranges[name];
  8302. };
  8303. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8304. var range = this.getAnimationRange(name);
  8305. if (!range) {
  8306. return null;
  8307. }
  8308. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8309. };
  8310. Node.prototype.serializeAnimationRanges = function () {
  8311. var serializationRanges = [];
  8312. for (var name in this._ranges) {
  8313. var range = {};
  8314. range.name = name;
  8315. range.from = this._ranges[name].from;
  8316. range.to = this._ranges[name].to;
  8317. serializationRanges.push(range);
  8318. }
  8319. return serializationRanges;
  8320. };
  8321. Node.prototype.dispose = function () {
  8322. this.parent = null;
  8323. };
  8324. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8325. if (parsedNode.ranges) {
  8326. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8327. var data = parsedNode.ranges[index];
  8328. node.createAnimationRange(data.name, data.from, data.to);
  8329. }
  8330. }
  8331. };
  8332. __decorate([
  8333. BABYLON.serialize()
  8334. ], Node.prototype, "name", void 0);
  8335. __decorate([
  8336. BABYLON.serialize()
  8337. ], Node.prototype, "id", void 0);
  8338. __decorate([
  8339. BABYLON.serialize()
  8340. ], Node.prototype, "uniqueId", void 0);
  8341. __decorate([
  8342. BABYLON.serialize()
  8343. ], Node.prototype, "state", void 0);
  8344. return Node;
  8345. })();
  8346. BABYLON.Node = Node;
  8347. })(BABYLON || (BABYLON = {}));
  8348. var BABYLON;
  8349. (function (BABYLON) {
  8350. var FilesInput = (function () {
  8351. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8352. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8353. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8354. this._engine = p_engine;
  8355. this._canvas = p_canvas;
  8356. this._currentScene = p_scene;
  8357. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8358. this._progressCallback = p_progressCallback;
  8359. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8360. this._textureLoadingCallback = p_textureLoadingCallback;
  8361. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8362. }
  8363. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8364. var _this = this;
  8365. if (p_elementToMonitor) {
  8366. this._elementToMonitor = p_elementToMonitor;
  8367. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8368. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8369. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8370. }
  8371. };
  8372. FilesInput.prototype.renderFunction = function () {
  8373. if (this._additionnalRenderLoopLogicCallback) {
  8374. this._additionnalRenderLoopLogicCallback();
  8375. }
  8376. if (this._currentScene) {
  8377. if (this._textureLoadingCallback) {
  8378. var remaining = this._currentScene.getWaitingItemsCount();
  8379. if (remaining > 0) {
  8380. this._textureLoadingCallback(remaining);
  8381. }
  8382. }
  8383. this._currentScene.render();
  8384. }
  8385. };
  8386. FilesInput.prototype.drag = function (e) {
  8387. e.stopPropagation();
  8388. e.preventDefault();
  8389. };
  8390. FilesInput.prototype.drop = function (eventDrop) {
  8391. eventDrop.stopPropagation();
  8392. eventDrop.preventDefault();
  8393. this.loadFiles(eventDrop);
  8394. };
  8395. FilesInput.prototype.loadFiles = function (event) {
  8396. if (this._startingProcessingFilesCallback)
  8397. this._startingProcessingFilesCallback();
  8398. // Handling data transfer via drag'n'drop
  8399. if (event && event.dataTransfer && event.dataTransfer.files) {
  8400. this._filesToLoad = event.dataTransfer.files;
  8401. }
  8402. // Handling files from input files
  8403. if (event && event.target && event.target.files) {
  8404. this._filesToLoad = event.target.files;
  8405. }
  8406. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8407. for (var i = 0; i < this._filesToLoad.length; i++) {
  8408. switch (this._filesToLoad[i].type) {
  8409. case "image/jpeg":
  8410. case "image/png":
  8411. case "image/bmp":
  8412. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8413. break;
  8414. case "image/targa":
  8415. case "image/vnd.ms-dds":
  8416. case "audio/wav":
  8417. case "audio/x-wav":
  8418. case "audio/mp3":
  8419. case "audio/mpeg":
  8420. case "audio/mpeg3":
  8421. case "audio/x-mpeg-3":
  8422. case "audio/ogg":
  8423. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8424. break;
  8425. default:
  8426. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8427. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8428. }
  8429. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8430. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8431. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8432. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8433. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8434. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8435. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8436. this._sceneFileToLoad = this._filesToLoad[i];
  8437. }
  8438. break;
  8439. }
  8440. }
  8441. this.reload();
  8442. }
  8443. };
  8444. FilesInput.prototype.reload = function () {
  8445. var _this = this;
  8446. var that = this;
  8447. // If a ".babylon" file has been provided
  8448. if (this._sceneFileToLoad) {
  8449. if (this._currentScene) {
  8450. if (BABYLON.Tools.errorsCount > 0) {
  8451. BABYLON.Tools.ClearLogCache();
  8452. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8453. }
  8454. this._engine.stopRenderLoop();
  8455. this._currentScene.dispose();
  8456. }
  8457. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8458. that._currentScene = newScene;
  8459. // Wait for textures and shaders to be ready
  8460. that._currentScene.executeWhenReady(function () {
  8461. // Attach camera to canvas inputs
  8462. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8463. that._currentScene.createDefaultCameraOrLight();
  8464. }
  8465. that._currentScene.activeCamera.attachControl(that._canvas);
  8466. if (that._sceneLoadedCallback) {
  8467. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8468. }
  8469. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8470. });
  8471. }, function (progress) {
  8472. if (_this._progressCallback) {
  8473. _this._progressCallback(progress);
  8474. }
  8475. });
  8476. }
  8477. else {
  8478. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8479. }
  8480. };
  8481. FilesInput.FilesTextures = new Array();
  8482. FilesInput.FilesToLoad = new Array();
  8483. return FilesInput;
  8484. })();
  8485. BABYLON.FilesInput = FilesInput;
  8486. })(BABYLON || (BABYLON = {}));
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. var IntersectionInfo = (function () {
  8490. function IntersectionInfo(bu, bv, distance) {
  8491. this.bu = bu;
  8492. this.bv = bv;
  8493. this.distance = distance;
  8494. this.faceId = 0;
  8495. this.subMeshId = 0;
  8496. }
  8497. return IntersectionInfo;
  8498. })();
  8499. BABYLON.IntersectionInfo = IntersectionInfo;
  8500. var PickingInfo = (function () {
  8501. function PickingInfo() {
  8502. this.hit = false;
  8503. this.distance = 0;
  8504. this.pickedPoint = null;
  8505. this.pickedMesh = null;
  8506. this.bu = 0;
  8507. this.bv = 0;
  8508. this.faceId = -1;
  8509. this.subMeshId = 0;
  8510. this.pickedSprite = null;
  8511. }
  8512. // Methods
  8513. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8514. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8515. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8516. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8517. return null;
  8518. }
  8519. var indices = this.pickedMesh.getIndices();
  8520. var result;
  8521. if (useVerticesNormals) {
  8522. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8523. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8524. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8525. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8526. normal0 = normal0.scale(this.bu);
  8527. normal1 = normal1.scale(this.bv);
  8528. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8529. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8530. }
  8531. else {
  8532. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8533. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8534. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8535. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8536. var p1p2 = vertex1.subtract(vertex2);
  8537. var p3p2 = vertex3.subtract(vertex2);
  8538. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8539. }
  8540. if (useWorldCoordinates) {
  8541. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8542. }
  8543. return BABYLON.Vector3.Normalize(result);
  8544. };
  8545. PickingInfo.prototype.getTextureCoordinates = function () {
  8546. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8547. return null;
  8548. }
  8549. var indices = this.pickedMesh.getIndices();
  8550. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8551. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8552. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8553. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8554. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8555. uv1 = uv1.scale(this.bu);
  8556. uv2 = uv2.scale(this.bv);
  8557. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8558. };
  8559. return PickingInfo;
  8560. })();
  8561. BABYLON.PickingInfo = PickingInfo;
  8562. })(BABYLON || (BABYLON = {}));
  8563. var BABYLON;
  8564. (function (BABYLON) {
  8565. var BoundingSphere = (function () {
  8566. function BoundingSphere(minimum, maximum) {
  8567. this.minimum = minimum;
  8568. this.maximum = maximum;
  8569. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8570. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8571. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8572. this.radius = distance * 0.5;
  8573. this.centerWorld = BABYLON.Vector3.Zero();
  8574. this._update(BABYLON.Matrix.Identity());
  8575. }
  8576. // Methods
  8577. BoundingSphere.prototype._update = function (world) {
  8578. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8579. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8580. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8581. };
  8582. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8583. for (var i = 0; i < 6; i++) {
  8584. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8585. return false;
  8586. }
  8587. return true;
  8588. };
  8589. BoundingSphere.prototype.intersectsPoint = function (point) {
  8590. var x = this.centerWorld.x - point.x;
  8591. var y = this.centerWorld.y - point.y;
  8592. var z = this.centerWorld.z - point.z;
  8593. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8594. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8595. return false;
  8596. return true;
  8597. };
  8598. // Statics
  8599. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8600. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8601. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8602. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8603. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8604. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8605. return false;
  8606. return true;
  8607. };
  8608. return BoundingSphere;
  8609. })();
  8610. BABYLON.BoundingSphere = BoundingSphere;
  8611. })(BABYLON || (BABYLON = {}));
  8612. var BABYLON;
  8613. (function (BABYLON) {
  8614. var BoundingBox = (function () {
  8615. function BoundingBox(minimum, maximum) {
  8616. this.minimum = minimum;
  8617. this.maximum = maximum;
  8618. this.vectors = new Array();
  8619. this.vectorsWorld = new Array();
  8620. // Bounding vectors
  8621. this.vectors.push(this.minimum.clone());
  8622. this.vectors.push(this.maximum.clone());
  8623. this.vectors.push(this.minimum.clone());
  8624. this.vectors[2].x = this.maximum.x;
  8625. this.vectors.push(this.minimum.clone());
  8626. this.vectors[3].y = this.maximum.y;
  8627. this.vectors.push(this.minimum.clone());
  8628. this.vectors[4].z = this.maximum.z;
  8629. this.vectors.push(this.maximum.clone());
  8630. this.vectors[5].z = this.minimum.z;
  8631. this.vectors.push(this.maximum.clone());
  8632. this.vectors[6].x = this.minimum.x;
  8633. this.vectors.push(this.maximum.clone());
  8634. this.vectors[7].y = this.minimum.y;
  8635. // OBB
  8636. this.center = this.maximum.add(this.minimum).scale(0.5);
  8637. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8638. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8639. // World
  8640. for (var index = 0; index < this.vectors.length; index++) {
  8641. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8642. }
  8643. this.minimumWorld = BABYLON.Vector3.Zero();
  8644. this.maximumWorld = BABYLON.Vector3.Zero();
  8645. this._update(BABYLON.Matrix.Identity());
  8646. }
  8647. // Methods
  8648. BoundingBox.prototype.getWorldMatrix = function () {
  8649. return this._worldMatrix;
  8650. };
  8651. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8652. this._worldMatrix.copyFrom(matrix);
  8653. return this;
  8654. };
  8655. BoundingBox.prototype._update = function (world) {
  8656. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8657. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8658. for (var index = 0; index < this.vectors.length; index++) {
  8659. var v = this.vectorsWorld[index];
  8660. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8661. if (v.x < this.minimumWorld.x)
  8662. this.minimumWorld.x = v.x;
  8663. if (v.y < this.minimumWorld.y)
  8664. this.minimumWorld.y = v.y;
  8665. if (v.z < this.minimumWorld.z)
  8666. this.minimumWorld.z = v.z;
  8667. if (v.x > this.maximumWorld.x)
  8668. this.maximumWorld.x = v.x;
  8669. if (v.y > this.maximumWorld.y)
  8670. this.maximumWorld.y = v.y;
  8671. if (v.z > this.maximumWorld.z)
  8672. this.maximumWorld.z = v.z;
  8673. }
  8674. // OBB
  8675. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8676. this.center.scaleInPlace(0.5);
  8677. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8678. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8679. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8680. this._worldMatrix = world;
  8681. };
  8682. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8683. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8684. };
  8685. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8686. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8687. };
  8688. BoundingBox.prototype.intersectsPoint = function (point) {
  8689. var delta = -BABYLON.Epsilon;
  8690. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8691. return false;
  8692. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8693. return false;
  8694. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8695. return false;
  8696. return true;
  8697. };
  8698. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8699. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8700. };
  8701. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8702. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8703. return false;
  8704. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8705. return false;
  8706. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8707. return false;
  8708. return true;
  8709. };
  8710. // Statics
  8711. BoundingBox.Intersects = function (box0, box1) {
  8712. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8713. return false;
  8714. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8715. return false;
  8716. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8717. return false;
  8718. return true;
  8719. };
  8720. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8721. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8722. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8723. return (num <= (sphereRadius * sphereRadius));
  8724. };
  8725. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8726. for (var p = 0; p < 6; p++) {
  8727. for (var i = 0; i < 8; i++) {
  8728. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8729. return false;
  8730. }
  8731. }
  8732. }
  8733. return true;
  8734. };
  8735. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8736. for (var p = 0; p < 6; p++) {
  8737. var inCount = 8;
  8738. for (var i = 0; i < 8; i++) {
  8739. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8740. --inCount;
  8741. }
  8742. else {
  8743. break;
  8744. }
  8745. }
  8746. if (inCount === 0)
  8747. return false;
  8748. }
  8749. return true;
  8750. };
  8751. return BoundingBox;
  8752. })();
  8753. BABYLON.BoundingBox = BoundingBox;
  8754. })(BABYLON || (BABYLON = {}));
  8755. var BABYLON;
  8756. (function (BABYLON) {
  8757. var computeBoxExtents = function (axis, box) {
  8758. var p = BABYLON.Vector3.Dot(box.center, axis);
  8759. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8760. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8761. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8762. var r = r0 + r1 + r2;
  8763. return {
  8764. min: p - r,
  8765. max: p + r
  8766. };
  8767. };
  8768. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8769. var axisOverlap = function (axis, box0, box1) {
  8770. var result0 = computeBoxExtents(axis, box0);
  8771. var result1 = computeBoxExtents(axis, box1);
  8772. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8773. };
  8774. var BoundingInfo = (function () {
  8775. function BoundingInfo(minimum, maximum) {
  8776. this.minimum = minimum;
  8777. this.maximum = maximum;
  8778. this._isLocked = false;
  8779. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8780. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8781. }
  8782. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8783. get: function () {
  8784. return this._isLocked;
  8785. },
  8786. set: function (value) {
  8787. this._isLocked = value;
  8788. },
  8789. enumerable: true,
  8790. configurable: true
  8791. });
  8792. // Methods
  8793. BoundingInfo.prototype.update = function (world) {
  8794. if (this._isLocked) {
  8795. return;
  8796. }
  8797. this.boundingBox._update(world);
  8798. this.boundingSphere._update(world);
  8799. };
  8800. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8801. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8802. return false;
  8803. return this.boundingBox.isInFrustum(frustumPlanes);
  8804. };
  8805. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8806. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8807. };
  8808. BoundingInfo.prototype._checkCollision = function (collider) {
  8809. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8810. };
  8811. BoundingInfo.prototype.intersectsPoint = function (point) {
  8812. if (!this.boundingSphere.centerWorld) {
  8813. return false;
  8814. }
  8815. if (!this.boundingSphere.intersectsPoint(point)) {
  8816. return false;
  8817. }
  8818. if (!this.boundingBox.intersectsPoint(point)) {
  8819. return false;
  8820. }
  8821. return true;
  8822. };
  8823. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8824. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8825. return false;
  8826. }
  8827. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8828. return false;
  8829. }
  8830. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8831. return false;
  8832. }
  8833. if (!precise) {
  8834. return true;
  8835. }
  8836. var box0 = this.boundingBox;
  8837. var box1 = boundingInfo.boundingBox;
  8838. if (!axisOverlap(box0.directions[0], box0, box1))
  8839. return false;
  8840. if (!axisOverlap(box0.directions[1], box0, box1))
  8841. return false;
  8842. if (!axisOverlap(box0.directions[2], box0, box1))
  8843. return false;
  8844. if (!axisOverlap(box1.directions[0], box0, box1))
  8845. return false;
  8846. if (!axisOverlap(box1.directions[1], box0, box1))
  8847. return false;
  8848. if (!axisOverlap(box1.directions[2], box0, box1))
  8849. return false;
  8850. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8851. return false;
  8852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8853. return false;
  8854. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8855. return false;
  8856. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8857. return false;
  8858. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8859. return false;
  8860. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8861. return false;
  8862. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8863. return false;
  8864. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8865. return false;
  8866. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8867. return false;
  8868. return true;
  8869. };
  8870. return BoundingInfo;
  8871. })();
  8872. BABYLON.BoundingInfo = BoundingInfo;
  8873. })(BABYLON || (BABYLON = {}));
  8874. var BABYLON;
  8875. (function (BABYLON) {
  8876. var Ray = (function () {
  8877. function Ray(origin, direction, length) {
  8878. if (length === void 0) { length = Number.MAX_VALUE; }
  8879. this.origin = origin;
  8880. this.direction = direction;
  8881. this.length = length;
  8882. }
  8883. // Methods
  8884. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8885. var d = 0.0;
  8886. var maxValue = Number.MAX_VALUE;
  8887. var inv;
  8888. var min;
  8889. var max;
  8890. var temp;
  8891. if (Math.abs(this.direction.x) < 0.0000001) {
  8892. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8893. return false;
  8894. }
  8895. }
  8896. else {
  8897. inv = 1.0 / this.direction.x;
  8898. min = (minimum.x - this.origin.x) * inv;
  8899. max = (maximum.x - this.origin.x) * inv;
  8900. if (max === -Infinity) {
  8901. max = Infinity;
  8902. }
  8903. if (min > max) {
  8904. temp = min;
  8905. min = max;
  8906. max = temp;
  8907. }
  8908. d = Math.max(min, d);
  8909. maxValue = Math.min(max, maxValue);
  8910. if (d > maxValue) {
  8911. return false;
  8912. }
  8913. }
  8914. if (Math.abs(this.direction.y) < 0.0000001) {
  8915. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8916. return false;
  8917. }
  8918. }
  8919. else {
  8920. inv = 1.0 / this.direction.y;
  8921. min = (minimum.y - this.origin.y) * inv;
  8922. max = (maximum.y - this.origin.y) * inv;
  8923. if (max === -Infinity) {
  8924. max = Infinity;
  8925. }
  8926. if (min > max) {
  8927. temp = min;
  8928. min = max;
  8929. max = temp;
  8930. }
  8931. d = Math.max(min, d);
  8932. maxValue = Math.min(max, maxValue);
  8933. if (d > maxValue) {
  8934. return false;
  8935. }
  8936. }
  8937. if (Math.abs(this.direction.z) < 0.0000001) {
  8938. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8939. return false;
  8940. }
  8941. }
  8942. else {
  8943. inv = 1.0 / this.direction.z;
  8944. min = (minimum.z - this.origin.z) * inv;
  8945. max = (maximum.z - this.origin.z) * inv;
  8946. if (max === -Infinity) {
  8947. max = Infinity;
  8948. }
  8949. if (min > max) {
  8950. temp = min;
  8951. min = max;
  8952. max = temp;
  8953. }
  8954. d = Math.max(min, d);
  8955. maxValue = Math.min(max, maxValue);
  8956. if (d > maxValue) {
  8957. return false;
  8958. }
  8959. }
  8960. return true;
  8961. };
  8962. Ray.prototype.intersectsBox = function (box) {
  8963. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8964. };
  8965. Ray.prototype.intersectsSphere = function (sphere) {
  8966. var x = sphere.center.x - this.origin.x;
  8967. var y = sphere.center.y - this.origin.y;
  8968. var z = sphere.center.z - this.origin.z;
  8969. var pyth = (x * x) + (y * y) + (z * z);
  8970. var rr = sphere.radius * sphere.radius;
  8971. if (pyth <= rr) {
  8972. return true;
  8973. }
  8974. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8975. if (dot < 0.0) {
  8976. return false;
  8977. }
  8978. var temp = pyth - (dot * dot);
  8979. return temp <= rr;
  8980. };
  8981. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8982. if (!this._edge1) {
  8983. this._edge1 = BABYLON.Vector3.Zero();
  8984. this._edge2 = BABYLON.Vector3.Zero();
  8985. this._pvec = BABYLON.Vector3.Zero();
  8986. this._tvec = BABYLON.Vector3.Zero();
  8987. this._qvec = BABYLON.Vector3.Zero();
  8988. }
  8989. vertex1.subtractToRef(vertex0, this._edge1);
  8990. vertex2.subtractToRef(vertex0, this._edge2);
  8991. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8992. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8993. if (det === 0) {
  8994. return null;
  8995. }
  8996. var invdet = 1 / det;
  8997. this.origin.subtractToRef(vertex0, this._tvec);
  8998. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8999. if (bu < 0 || bu > 1.0) {
  9000. return null;
  9001. }
  9002. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9003. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9004. if (bv < 0 || bu + bv > 1.0) {
  9005. return null;
  9006. }
  9007. //check if the distance is longer than the predefined length.
  9008. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9009. if (distance > this.length) {
  9010. return null;
  9011. }
  9012. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9013. };
  9014. Ray.prototype.intersectsPlane = function (plane) {
  9015. var distance;
  9016. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9017. if (Math.abs(result1) < 9.99999997475243E-07) {
  9018. return null;
  9019. }
  9020. else {
  9021. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9022. distance = (-plane.d - result2) / result1;
  9023. if (distance < 0.0) {
  9024. if (distance < -9.99999997475243E-07) {
  9025. return null;
  9026. }
  9027. else {
  9028. return 0;
  9029. }
  9030. }
  9031. return distance;
  9032. }
  9033. };
  9034. /**
  9035. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9036. * @param sega the first point of the segment to test the intersection against
  9037. * @param segb the second point of the segment to test the intersection against
  9038. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9039. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9040. */
  9041. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9042. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9043. var u = segb.subtract(sega);
  9044. var v = rsegb.subtract(this.origin);
  9045. var w = sega.subtract(this.origin);
  9046. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9047. var b = BABYLON.Vector3.Dot(u, v);
  9048. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9049. var d = BABYLON.Vector3.Dot(u, w);
  9050. var e = BABYLON.Vector3.Dot(v, w);
  9051. var D = a * c - b * b; // always >= 0
  9052. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9053. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9054. // compute the line parameters of the two closest points
  9055. if (D < Ray.smallnum) {
  9056. sN = 0.0; // force using point P0 on segment S1
  9057. sD = 1.0; // to prevent possible division by 0.0 later
  9058. tN = e;
  9059. tD = c;
  9060. }
  9061. else {
  9062. sN = (b * e - c * d);
  9063. tN = (a * e - b * d);
  9064. if (sN < 0.0) {
  9065. sN = 0.0;
  9066. tN = e;
  9067. tD = c;
  9068. }
  9069. else if (sN > sD) {
  9070. sN = sD;
  9071. tN = e + b;
  9072. tD = c;
  9073. }
  9074. }
  9075. if (tN < 0.0) {
  9076. tN = 0.0;
  9077. // recompute sc for this edge
  9078. if (-d < 0.0) {
  9079. sN = 0.0;
  9080. }
  9081. else if (-d > a)
  9082. sN = sD;
  9083. else {
  9084. sN = -d;
  9085. sD = a;
  9086. }
  9087. }
  9088. else if (tN > tD) {
  9089. tN = tD;
  9090. // recompute sc for this edge
  9091. if ((-d + b) < 0.0) {
  9092. sN = 0;
  9093. }
  9094. else if ((-d + b) > a) {
  9095. sN = sD;
  9096. }
  9097. else {
  9098. sN = (-d + b);
  9099. sD = a;
  9100. }
  9101. }
  9102. // finally do the division to get sc and tc
  9103. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9104. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9105. // get the difference of the two closest points
  9106. var qtc = v.multiplyByFloats(tc, tc, tc);
  9107. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9108. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9109. if (isIntersected) {
  9110. return qtc.length();
  9111. }
  9112. return -1;
  9113. };
  9114. // Statics
  9115. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9116. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9117. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9118. var direction = end.subtract(start);
  9119. direction.normalize();
  9120. return new Ray(start, direction);
  9121. };
  9122. /**
  9123. * 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
  9124. * transformed to the given world matrix.
  9125. * @param origin The origin point
  9126. * @param end The end point
  9127. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9128. */
  9129. Ray.CreateNewFromTo = function (origin, end, world) {
  9130. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9131. var direction = end.subtract(origin);
  9132. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9133. direction.normalize();
  9134. return Ray.Transform(new Ray(origin, direction, length), world);
  9135. };
  9136. Ray.Transform = function (ray, matrix) {
  9137. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9138. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9139. newDirection.normalize();
  9140. return new Ray(newOrigin, newDirection, ray.length);
  9141. };
  9142. Ray.smallnum = 0.00000001;
  9143. Ray.rayl = 10e8;
  9144. return Ray;
  9145. })();
  9146. BABYLON.Ray = Ray;
  9147. })(BABYLON || (BABYLON = {}));
  9148. var BABYLON;
  9149. (function (BABYLON) {
  9150. var AbstractMesh = (function (_super) {
  9151. __extends(AbstractMesh, _super);
  9152. // Constructor
  9153. function AbstractMesh(name, scene) {
  9154. var _this = this;
  9155. _super.call(this, name, scene);
  9156. // Events
  9157. /**
  9158. * An event triggered when the mesh is disposed.
  9159. * @type {BABYLON.Observable}
  9160. */
  9161. this.onDisposeObservable = new BABYLON.Observable();
  9162. /**
  9163. * An event triggered when this mesh collides with another one
  9164. * @type {BABYLON.Observable}
  9165. */
  9166. this.onCollideObservable = new BABYLON.Observable();
  9167. /**
  9168. * An event triggered when the collision's position changes
  9169. * @type {BABYLON.Observable}
  9170. */
  9171. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9172. /**
  9173. * An event triggered after the world matrix is updated
  9174. * @type {BABYLON.Observable}
  9175. */
  9176. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9177. // Properties
  9178. this.definedFacingForward = true; // orientation for POV movement & rotation
  9179. this.position = new BABYLON.Vector3(0, 0, 0);
  9180. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9181. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9182. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9183. this.visibility = 1.0;
  9184. this.alphaIndex = Number.MAX_VALUE;
  9185. this.infiniteDistance = false;
  9186. this.isVisible = true;
  9187. this.isPickable = true;
  9188. this.showBoundingBox = false;
  9189. this.showSubMeshesBoundingBox = false;
  9190. this.isBlocker = false;
  9191. this.renderingGroupId = 0;
  9192. this.receiveShadows = false;
  9193. this.renderOutline = false;
  9194. this.outlineColor = BABYLON.Color3.Red();
  9195. this.outlineWidth = 0.02;
  9196. this.renderOverlay = false;
  9197. this.overlayColor = BABYLON.Color3.Red();
  9198. this.overlayAlpha = 0.5;
  9199. this.hasVertexAlpha = false;
  9200. this.useVertexColors = true;
  9201. this.applyFog = true;
  9202. this.computeBonesUsingShaders = true;
  9203. this.scalingDeterminant = 1;
  9204. this.numBoneInfluencers = 4;
  9205. this.useOctreeForRenderingSelection = true;
  9206. this.useOctreeForPicking = true;
  9207. this.useOctreeForCollisions = true;
  9208. this.layerMask = 0x0FFFFFFF;
  9209. this.alwaysSelectAsActiveMesh = false;
  9210. // Collisions
  9211. this._checkCollisions = false;
  9212. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9213. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9214. this._collider = new BABYLON.Collider();
  9215. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9216. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9217. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9218. // Edges
  9219. this.edgesWidth = 1;
  9220. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9221. // Cache
  9222. this._localWorld = BABYLON.Matrix.Zero();
  9223. this._worldMatrix = BABYLON.Matrix.Zero();
  9224. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9225. this._absolutePosition = BABYLON.Vector3.Zero();
  9226. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9227. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9228. this._isDirty = false;
  9229. this._pivotMatrix = BABYLON.Matrix.Identity();
  9230. this._isDisposed = false;
  9231. this._renderId = 0;
  9232. this._intersectionsInProgress = new Array();
  9233. this._isWorldMatrixFrozen = false;
  9234. this._unIndexed = false;
  9235. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9236. if (collidedMesh === void 0) { collidedMesh = null; }
  9237. //TODO move this to the collision coordinator!
  9238. if (_this.getScene().workerCollisions)
  9239. newPosition.multiplyInPlace(_this._collider.radius);
  9240. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9241. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9242. _this.position.addInPlace(_this._diffPositionForCollisions);
  9243. }
  9244. if (collidedMesh) {
  9245. _this.onCollideObservable.notifyObservers(collidedMesh);
  9246. }
  9247. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9248. };
  9249. scene.addMesh(this);
  9250. }
  9251. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9252. get: function () {
  9253. return AbstractMesh._BILLBOARDMODE_NONE;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9259. get: function () {
  9260. return AbstractMesh._BILLBOARDMODE_X;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9266. get: function () {
  9267. return AbstractMesh._BILLBOARDMODE_Y;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9273. get: function () {
  9274. return AbstractMesh._BILLBOARDMODE_Z;
  9275. },
  9276. enumerable: true,
  9277. configurable: true
  9278. });
  9279. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9280. get: function () {
  9281. return AbstractMesh._BILLBOARDMODE_ALL;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9287. set: function (callback) {
  9288. if (this._onDisposeObserver) {
  9289. this.onDisposeObservable.remove(this._onDisposeObserver);
  9290. }
  9291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9297. set: function (callback) {
  9298. if (this._onCollideObserver) {
  9299. this.onCollideObservable.remove(this._onCollideObserver);
  9300. }
  9301. this._onCollideObserver = this.onCollideObservable.add(callback);
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9307. set: function (callback) {
  9308. if (this._onCollisionPositionChangeObserver) {
  9309. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9310. }
  9311. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9312. },
  9313. enumerable: true,
  9314. configurable: true
  9315. });
  9316. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9317. get: function () {
  9318. return this._skeleton;
  9319. },
  9320. set: function (value) {
  9321. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9322. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9323. }
  9324. if (value && value.needInitialSkinMatrix) {
  9325. value._registerMeshWithPoseMatrix(this);
  9326. }
  9327. this._skeleton = value;
  9328. if (!this._skeleton) {
  9329. this._bonesTransformMatrices = null;
  9330. }
  9331. },
  9332. enumerable: true,
  9333. configurable: true
  9334. });
  9335. /**
  9336. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9337. */
  9338. AbstractMesh.prototype.toString = function (fullDetails) {
  9339. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9340. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9341. if (this._skeleton) {
  9342. ret += ", skeleton: " + this._skeleton.name;
  9343. }
  9344. if (fullDetails) {
  9345. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9346. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9347. }
  9348. return ret;
  9349. };
  9350. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9351. /**
  9352. * Getting the rotation object.
  9353. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9354. */
  9355. get: function () {
  9356. return this._rotation;
  9357. },
  9358. set: function (newRotation) {
  9359. this._rotation = newRotation;
  9360. },
  9361. enumerable: true,
  9362. configurable: true
  9363. });
  9364. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9365. get: function () {
  9366. return this._scaling;
  9367. },
  9368. set: function (newScaling) {
  9369. this._scaling = newScaling;
  9370. if (this.physicsImpostor) {
  9371. this.physicsImpostor.forceUpdate();
  9372. }
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9378. get: function () {
  9379. return this._rotationQuaternion;
  9380. },
  9381. set: function (quaternion) {
  9382. this._rotationQuaternion = quaternion;
  9383. //reset the rotation vector.
  9384. if (quaternion && this.rotation.length()) {
  9385. this.rotation.copyFromFloats(0, 0, 0);
  9386. }
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. // Methods
  9392. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9393. this._poseMatrix.copyFrom(matrix);
  9394. };
  9395. AbstractMesh.prototype.getPoseMatrix = function () {
  9396. return this._poseMatrix;
  9397. };
  9398. AbstractMesh.prototype.disableEdgesRendering = function () {
  9399. if (this._edgesRenderer !== undefined) {
  9400. this._edgesRenderer.dispose();
  9401. this._edgesRenderer = undefined;
  9402. }
  9403. };
  9404. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9405. if (epsilon === void 0) { epsilon = 0.95; }
  9406. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9407. this.disableEdgesRendering();
  9408. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9409. };
  9410. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9411. get: function () {
  9412. return false;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. AbstractMesh.prototype.getLOD = function (camera) {
  9418. return this;
  9419. };
  9420. AbstractMesh.prototype.getTotalVertices = function () {
  9421. return 0;
  9422. };
  9423. AbstractMesh.prototype.getIndices = function () {
  9424. return null;
  9425. };
  9426. AbstractMesh.prototype.getVerticesData = function (kind) {
  9427. return null;
  9428. };
  9429. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9430. return false;
  9431. };
  9432. AbstractMesh.prototype.getBoundingInfo = function () {
  9433. if (this._masterMesh) {
  9434. return this._masterMesh.getBoundingInfo();
  9435. }
  9436. if (!this._boundingInfo) {
  9437. this._updateBoundingInfo();
  9438. }
  9439. return this._boundingInfo;
  9440. };
  9441. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9442. get: function () {
  9443. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. AbstractMesh.prototype._preActivate = function () {
  9449. };
  9450. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9451. };
  9452. AbstractMesh.prototype._activate = function (renderId) {
  9453. this._renderId = renderId;
  9454. };
  9455. AbstractMesh.prototype.getWorldMatrix = function () {
  9456. if (this._masterMesh) {
  9457. return this._masterMesh.getWorldMatrix();
  9458. }
  9459. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9460. this.computeWorldMatrix();
  9461. }
  9462. return this._worldMatrix;
  9463. };
  9464. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9465. get: function () {
  9466. return this._worldMatrix;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9472. get: function () {
  9473. return this._absolutePosition;
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9479. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9480. this.computeWorldMatrix(true);
  9481. this._isWorldMatrixFrozen = true;
  9482. };
  9483. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9484. this._isWorldMatrixFrozen = false;
  9485. this.computeWorldMatrix(true);
  9486. };
  9487. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9488. get: function () {
  9489. return this._isWorldMatrixFrozen;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9495. axis.normalize();
  9496. if (!this.rotationQuaternion) {
  9497. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9498. this.rotation = BABYLON.Vector3.Zero();
  9499. }
  9500. var rotationQuaternion;
  9501. if (!space || space === BABYLON.Space.LOCAL) {
  9502. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9503. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9504. }
  9505. else {
  9506. if (this.parent) {
  9507. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9508. invertParentWorldMatrix.invert();
  9509. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9510. }
  9511. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9512. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9513. }
  9514. };
  9515. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9516. var displacementVector = axis.scale(distance);
  9517. if (!space || space === BABYLON.Space.LOCAL) {
  9518. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9519. this.setPositionWithLocalVector(tempV3);
  9520. }
  9521. else {
  9522. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9523. }
  9524. };
  9525. AbstractMesh.prototype.getAbsolutePosition = function () {
  9526. this.computeWorldMatrix();
  9527. return this._absolutePosition;
  9528. };
  9529. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9530. if (!absolutePosition) {
  9531. return;
  9532. }
  9533. var absolutePositionX;
  9534. var absolutePositionY;
  9535. var absolutePositionZ;
  9536. if (absolutePosition.x === undefined) {
  9537. if (arguments.length < 3) {
  9538. return;
  9539. }
  9540. absolutePositionX = arguments[0];
  9541. absolutePositionY = arguments[1];
  9542. absolutePositionZ = arguments[2];
  9543. }
  9544. else {
  9545. absolutePositionX = absolutePosition.x;
  9546. absolutePositionY = absolutePosition.y;
  9547. absolutePositionZ = absolutePosition.z;
  9548. }
  9549. if (this.parent) {
  9550. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9551. invertParentWorldMatrix.invert();
  9552. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9553. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9554. }
  9555. else {
  9556. this.position.x = absolutePositionX;
  9557. this.position.y = absolutePositionY;
  9558. this.position.z = absolutePositionZ;
  9559. }
  9560. };
  9561. // ================================== Point of View Movement =================================
  9562. /**
  9563. * Perform relative position change from the point of view of behind the front of the mesh.
  9564. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9565. * Supports definition of mesh facing forward or backward.
  9566. * @param {number} amountRight
  9567. * @param {number} amountUp
  9568. * @param {number} amountForward
  9569. */
  9570. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9571. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9572. };
  9573. /**
  9574. * Calculate relative position change from the point of view of behind the front of the mesh.
  9575. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9576. * Supports definition of mesh facing forward or backward.
  9577. * @param {number} amountRight
  9578. * @param {number} amountUp
  9579. * @param {number} amountForward
  9580. */
  9581. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9582. var rotMatrix = new BABYLON.Matrix();
  9583. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9584. rotQuaternion.toRotationMatrix(rotMatrix);
  9585. var translationDelta = BABYLON.Vector3.Zero();
  9586. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9588. return translationDelta;
  9589. };
  9590. // ================================== Point of View Rotation =================================
  9591. /**
  9592. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9593. * Supports definition of mesh facing forward or backward.
  9594. * @param {number} flipBack
  9595. * @param {number} twirlClockwise
  9596. * @param {number} tiltRight
  9597. */
  9598. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9599. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9600. };
  9601. /**
  9602. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9603. * Supports definition of mesh facing forward or backward.
  9604. * @param {number} flipBack
  9605. * @param {number} twirlClockwise
  9606. * @param {number} tiltRight
  9607. */
  9608. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9609. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9610. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9611. };
  9612. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9613. this._pivotMatrix = matrix;
  9614. this._cache.pivotMatrixUpdated = true;
  9615. };
  9616. AbstractMesh.prototype.getPivotMatrix = function () {
  9617. return this._pivotMatrix;
  9618. };
  9619. AbstractMesh.prototype._isSynchronized = function () {
  9620. if (this._isDirty) {
  9621. return false;
  9622. }
  9623. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9624. return false;
  9625. if (this._cache.pivotMatrixUpdated) {
  9626. return false;
  9627. }
  9628. if (this.infiniteDistance) {
  9629. return false;
  9630. }
  9631. if (!this._cache.position.equals(this.position))
  9632. return false;
  9633. if (this.rotationQuaternion) {
  9634. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9635. return false;
  9636. }
  9637. else {
  9638. if (!this._cache.rotation.equals(this.rotation))
  9639. return false;
  9640. }
  9641. if (!this._cache.scaling.equals(this.scaling))
  9642. return false;
  9643. return true;
  9644. };
  9645. AbstractMesh.prototype._initCache = function () {
  9646. _super.prototype._initCache.call(this);
  9647. this._cache.localMatrixUpdated = false;
  9648. this._cache.position = BABYLON.Vector3.Zero();
  9649. this._cache.scaling = BABYLON.Vector3.Zero();
  9650. this._cache.rotation = BABYLON.Vector3.Zero();
  9651. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9652. this._cache.billboardMode = -1;
  9653. };
  9654. AbstractMesh.prototype.markAsDirty = function (property) {
  9655. if (property === "rotation") {
  9656. this.rotationQuaternion = null;
  9657. }
  9658. this._currentRenderId = Number.MAX_VALUE;
  9659. this._isDirty = true;
  9660. };
  9661. AbstractMesh.prototype._updateBoundingInfo = function () {
  9662. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9663. this._boundingInfo.update(this.worldMatrixFromCache);
  9664. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9665. };
  9666. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9667. if (!this.subMeshes) {
  9668. return;
  9669. }
  9670. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9671. var subMesh = this.subMeshes[subIndex];
  9672. if (!subMesh.IsGlobal) {
  9673. subMesh.updateBoundingInfo(matrix);
  9674. }
  9675. }
  9676. };
  9677. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9678. if (this._isWorldMatrixFrozen) {
  9679. return this._worldMatrix;
  9680. }
  9681. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9682. this._currentRenderId = this.getScene().getRenderId();
  9683. return this._worldMatrix;
  9684. }
  9685. this._cache.position.copyFrom(this.position);
  9686. this._cache.scaling.copyFrom(this.scaling);
  9687. this._cache.pivotMatrixUpdated = false;
  9688. this._cache.billboardMode = this.billboardMode;
  9689. this._currentRenderId = this.getScene().getRenderId();
  9690. this._isDirty = false;
  9691. // Scaling
  9692. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9693. // Rotation
  9694. //rotate, if quaternion is set and rotation was used
  9695. if (this.rotationQuaternion) {
  9696. var len = this.rotation.length();
  9697. if (len) {
  9698. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9699. this.rotation.copyFromFloats(0, 0, 0);
  9700. }
  9701. }
  9702. if (this.rotationQuaternion) {
  9703. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9704. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9705. }
  9706. else {
  9707. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9708. this._cache.rotation.copyFrom(this.rotation);
  9709. }
  9710. // Translation
  9711. if (this.infiniteDistance && !this.parent) {
  9712. var camera = this.getScene().activeCamera;
  9713. if (camera) {
  9714. var cameraWorldMatrix = camera.getWorldMatrix();
  9715. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9716. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9717. }
  9718. }
  9719. else {
  9720. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9721. }
  9722. // Composing transformations
  9723. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9724. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9725. // Billboarding
  9726. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9727. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9728. var localPosition = BABYLON.Tmp.Vector3[0];
  9729. if (this.parent && this.parent.getWorldMatrix) {
  9730. this._markSyncedWithParent();
  9731. var parentMatrix;
  9732. if (this._meshToBoneReferal) {
  9733. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9734. parentMatrix = BABYLON.Tmp.Matrix[6];
  9735. }
  9736. else {
  9737. parentMatrix = this.parent.getWorldMatrix();
  9738. }
  9739. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9740. localPosition = BABYLON.Tmp.Vector3[1];
  9741. }
  9742. var zero = this.getScene().activeCamera.globalPosition.clone();
  9743. if (this.parent && this.parent.position) {
  9744. localPosition.addInPlace(this.parent.position);
  9745. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9746. }
  9747. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9748. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9749. zero.x = localPosition.x + BABYLON.Epsilon;
  9750. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9751. zero.y = localPosition.y + BABYLON.Epsilon;
  9752. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9753. zero.z = localPosition.z + BABYLON.Epsilon;
  9754. }
  9755. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9756. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9757. BABYLON.Tmp.Matrix[3].invert();
  9758. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9759. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9760. }
  9761. // Local world
  9762. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9763. // Parent
  9764. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9765. this._markSyncedWithParent();
  9766. if (this._meshToBoneReferal) {
  9767. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9768. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9769. }
  9770. else {
  9771. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9772. }
  9773. }
  9774. else {
  9775. this._worldMatrix.copyFrom(this._localWorld);
  9776. }
  9777. // Bounding info
  9778. this._updateBoundingInfo();
  9779. // Absolute position
  9780. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9781. // Callbacks
  9782. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9783. if (!this._poseMatrix) {
  9784. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9785. }
  9786. return this._worldMatrix;
  9787. };
  9788. /**
  9789. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9790. * @param func: callback function to add
  9791. */
  9792. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9793. this.onAfterWorldMatrixUpdateObservable.add(func);
  9794. };
  9795. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9796. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9797. };
  9798. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9799. this.computeWorldMatrix();
  9800. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9801. };
  9802. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9803. this.computeWorldMatrix();
  9804. var invLocalWorldMatrix = this._localWorld.clone();
  9805. invLocalWorldMatrix.invert();
  9806. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9807. };
  9808. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9809. this.computeWorldMatrix(true);
  9810. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9811. };
  9812. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9813. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9814. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9815. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9816. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9817. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9818. /// <returns>Mesh oriented towards targetMesh</returns>
  9819. if (yawCor === void 0) { yawCor = 0; }
  9820. if (pitchCor === void 0) { pitchCor = 0; }
  9821. if (rollCor === void 0) { rollCor = 0; }
  9822. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  9823. var dv = AbstractMesh._lookAtVectorCache;
  9824. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  9825. targetPoint.subtractToRef(pos, dv);
  9826. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9827. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9828. var pitch = Math.atan2(dv.y, len);
  9829. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  9830. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  9831. };
  9832. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9833. this._meshToBoneReferal = affectedMesh;
  9834. this.parent = bone;
  9835. if (bone.getWorldMatrix().determinant() < 0) {
  9836. this.scalingDeterminant *= -1;
  9837. }
  9838. };
  9839. AbstractMesh.prototype.detachFromBone = function () {
  9840. if (this.parent.getWorldMatrix().determinant() < 0) {
  9841. this.scalingDeterminant *= -1;
  9842. }
  9843. this._meshToBoneReferal = null;
  9844. this.parent = null;
  9845. };
  9846. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9847. return this._boundingInfo.isInFrustum(frustumPlanes);
  9848. };
  9849. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9850. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  9851. ;
  9852. };
  9853. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9854. if (!this._boundingInfo || !mesh._boundingInfo) {
  9855. return false;
  9856. }
  9857. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9858. };
  9859. AbstractMesh.prototype.intersectsPoint = function (point) {
  9860. if (!this._boundingInfo) {
  9861. return false;
  9862. }
  9863. return this._boundingInfo.intersectsPoint(point);
  9864. };
  9865. // Physics
  9866. /**
  9867. * @Deprecated. Use new PhysicsImpostor instead.
  9868. * */
  9869. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9870. //legacy support
  9871. if (impostor.impostor) {
  9872. options = impostor;
  9873. impostor = impostor.impostor;
  9874. }
  9875. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9876. return this.physicsImpostor.physicsBody;
  9877. };
  9878. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9879. return this.physicsImpostor;
  9880. };
  9881. /**
  9882. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9883. */
  9884. AbstractMesh.prototype.getPhysicsMass = function () {
  9885. return this.physicsImpostor.getParam("mass");
  9886. };
  9887. /**
  9888. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9889. */
  9890. AbstractMesh.prototype.getPhysicsFriction = function () {
  9891. return this.physicsImpostor.getParam("friction");
  9892. };
  9893. /**
  9894. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9895. */
  9896. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9897. return this.physicsImpostor.getParam("resitution");
  9898. };
  9899. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9900. if (!camera) {
  9901. camera = this.getScene().activeCamera;
  9902. }
  9903. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9904. };
  9905. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9906. if (!camera) {
  9907. camera = this.getScene().activeCamera;
  9908. }
  9909. return this.absolutePosition.subtract(camera.position).length();
  9910. };
  9911. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9912. if (!this.physicsImpostor) {
  9913. return;
  9914. }
  9915. this.physicsImpostor.applyImpulse(force, contactPoint);
  9916. };
  9917. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9918. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9919. return;
  9920. }
  9921. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9922. mainPivot: pivot1,
  9923. connectedPivot: pivot2,
  9924. nativeParams: options
  9925. });
  9926. };
  9927. /**
  9928. * @Deprecated
  9929. */
  9930. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9931. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9932. this.updatePhysicsBody();
  9933. };
  9934. /**
  9935. * @Deprecated
  9936. * Calling this function is not needed anymore.
  9937. * The physics engine takes care of transofmration automatically.
  9938. */
  9939. AbstractMesh.prototype.updatePhysicsBody = function () {
  9940. //Unneeded
  9941. };
  9942. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9943. // Collisions
  9944. get: function () {
  9945. return this._checkCollisions;
  9946. },
  9947. set: function (collisionEnabled) {
  9948. this._checkCollisions = collisionEnabled;
  9949. if (this.getScene().workerCollisions) {
  9950. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9951. }
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9957. var globalPosition = this.getAbsolutePosition();
  9958. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9959. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9960. this._collider.radius = this.ellipsoid;
  9961. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9962. };
  9963. // Submeshes octree
  9964. /**
  9965. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9966. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9967. */
  9968. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9969. if (maxCapacity === void 0) { maxCapacity = 64; }
  9970. if (maxDepth === void 0) { maxDepth = 2; }
  9971. if (!this._submeshesOctree) {
  9972. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9973. }
  9974. this.computeWorldMatrix(true);
  9975. // Update octree
  9976. var bbox = this.getBoundingInfo().boundingBox;
  9977. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9978. return this._submeshesOctree;
  9979. };
  9980. // Collisions
  9981. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9982. this._generatePointsArray();
  9983. // Transformation
  9984. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9985. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9986. subMesh._lastColliderWorldVertices = [];
  9987. subMesh._trianglePlanes = [];
  9988. var start = subMesh.verticesStart;
  9989. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9990. for (var i = start; i < end; i++) {
  9991. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9992. }
  9993. }
  9994. // Collide
  9995. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9996. if (collider.collisionFound) {
  9997. collider.collidedMesh = this;
  9998. }
  9999. };
  10000. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10001. var subMeshes;
  10002. var len;
  10003. // Octrees
  10004. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10005. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10006. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10007. len = intersections.length;
  10008. subMeshes = intersections.data;
  10009. }
  10010. else {
  10011. subMeshes = this.subMeshes;
  10012. len = subMeshes.length;
  10013. }
  10014. for (var index = 0; index < len; index++) {
  10015. var subMesh = subMeshes[index];
  10016. // Bounding test
  10017. if (len > 1 && !subMesh._checkCollision(collider))
  10018. continue;
  10019. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10020. }
  10021. };
  10022. AbstractMesh.prototype._checkCollision = function (collider) {
  10023. // Bounding box test
  10024. if (!this._boundingInfo._checkCollision(collider))
  10025. return;
  10026. // Transformation matrix
  10027. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10028. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10029. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10030. };
  10031. // Picking
  10032. AbstractMesh.prototype._generatePointsArray = function () {
  10033. return false;
  10034. };
  10035. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10036. var pickingInfo = new BABYLON.PickingInfo();
  10037. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10038. return pickingInfo;
  10039. }
  10040. if (!this._generatePointsArray()) {
  10041. return pickingInfo;
  10042. }
  10043. var intersectInfo = null;
  10044. // Octrees
  10045. var subMeshes;
  10046. var len;
  10047. if (this._submeshesOctree && this.useOctreeForPicking) {
  10048. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10049. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10050. len = intersections.length;
  10051. subMeshes = intersections.data;
  10052. }
  10053. else {
  10054. subMeshes = this.subMeshes;
  10055. len = subMeshes.length;
  10056. }
  10057. for (var index = 0; index < len; index++) {
  10058. var subMesh = subMeshes[index];
  10059. // Bounding test
  10060. if (len > 1 && !subMesh.canIntersects(ray))
  10061. continue;
  10062. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10063. if (currentIntersectInfo) {
  10064. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10065. intersectInfo = currentIntersectInfo;
  10066. intersectInfo.subMeshId = index;
  10067. if (fastCheck) {
  10068. break;
  10069. }
  10070. }
  10071. }
  10072. }
  10073. if (intersectInfo) {
  10074. // Get picked point
  10075. var world = this.getWorldMatrix();
  10076. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10077. var direction = ray.direction.clone();
  10078. direction = direction.scale(intersectInfo.distance);
  10079. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10080. var pickedPoint = worldOrigin.add(worldDirection);
  10081. // Return result
  10082. pickingInfo.hit = true;
  10083. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10084. pickingInfo.pickedPoint = pickedPoint;
  10085. pickingInfo.pickedMesh = this;
  10086. pickingInfo.bu = intersectInfo.bu;
  10087. pickingInfo.bv = intersectInfo.bv;
  10088. pickingInfo.faceId = intersectInfo.faceId;
  10089. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10090. return pickingInfo;
  10091. }
  10092. return pickingInfo;
  10093. };
  10094. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10095. return null;
  10096. };
  10097. AbstractMesh.prototype.releaseSubMeshes = function () {
  10098. if (this.subMeshes) {
  10099. while (this.subMeshes.length) {
  10100. this.subMeshes[0].dispose();
  10101. }
  10102. }
  10103. else {
  10104. this.subMeshes = new Array();
  10105. }
  10106. };
  10107. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10108. var _this = this;
  10109. var index;
  10110. // Action manager
  10111. if (this.actionManager) {
  10112. this.actionManager.dispose();
  10113. this.actionManager = null;
  10114. }
  10115. // Skeleton
  10116. this.skeleton = null;
  10117. // Animations
  10118. this.getScene().stopAnimation(this);
  10119. // Physics
  10120. if (this.physicsImpostor) {
  10121. this.physicsImpostor.dispose();
  10122. }
  10123. // Intersections in progress
  10124. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10125. var other = this._intersectionsInProgress[index];
  10126. var pos = other._intersectionsInProgress.indexOf(this);
  10127. other._intersectionsInProgress.splice(pos, 1);
  10128. }
  10129. this._intersectionsInProgress = [];
  10130. // Lights
  10131. var lights = this.getScene().lights;
  10132. lights.forEach(function (light) {
  10133. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10134. if (meshIndex !== -1) {
  10135. light.includedOnlyMeshes.splice(meshIndex, 1);
  10136. }
  10137. meshIndex = light.excludedMeshes.indexOf(_this);
  10138. if (meshIndex !== -1) {
  10139. light.excludedMeshes.splice(meshIndex, 1);
  10140. }
  10141. });
  10142. // Edges
  10143. if (this._edgesRenderer) {
  10144. this._edgesRenderer.dispose();
  10145. this._edgesRenderer = null;
  10146. }
  10147. // SubMeshes
  10148. this.releaseSubMeshes();
  10149. // Remove from scene
  10150. this.getScene().removeMesh(this);
  10151. if (!doNotRecurse) {
  10152. // Particles
  10153. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10154. if (this.getScene().particleSystems[index].emitter === this) {
  10155. this.getScene().particleSystems[index].dispose();
  10156. index--;
  10157. }
  10158. }
  10159. // Children
  10160. var objects = this.getDescendants(true);
  10161. for (index = 0; index < objects.length; index++) {
  10162. objects[index].dispose();
  10163. }
  10164. }
  10165. else {
  10166. var childMeshes = this.getChildMeshes(true);
  10167. for (index = 0; index < childMeshes.length; index++) {
  10168. var child = childMeshes[index];
  10169. child.parent = null;
  10170. child.computeWorldMatrix(true);
  10171. }
  10172. }
  10173. _super.prototype.dispose.call(this);
  10174. this.onAfterWorldMatrixUpdateObservable.clear();
  10175. this.onCollideObservable.clear();
  10176. this.onCollisionPositionChangeObservable.clear();
  10177. this._isDisposed = true;
  10178. // Callback
  10179. this.onDisposeObservable.notifyObservers(this);
  10180. this.onDisposeObservable.clear();
  10181. };
  10182. // Statics
  10183. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10184. AbstractMesh._BILLBOARDMODE_X = 1;
  10185. AbstractMesh._BILLBOARDMODE_Y = 2;
  10186. AbstractMesh._BILLBOARDMODE_Z = 4;
  10187. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10188. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10189. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10190. return AbstractMesh;
  10191. })(BABYLON.Node);
  10192. BABYLON.AbstractMesh = AbstractMesh;
  10193. })(BABYLON || (BABYLON = {}));
  10194. var BABYLON;
  10195. (function (BABYLON) {
  10196. var Light = (function (_super) {
  10197. __extends(Light, _super);
  10198. function Light(name, scene) {
  10199. _super.call(this, name, scene);
  10200. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10201. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10202. this.intensity = 1.0;
  10203. this.range = Number.MAX_VALUE;
  10204. this.includeOnlyWithLayerMask = 0;
  10205. this.includedOnlyMeshes = new Array();
  10206. this.excludedMeshes = new Array();
  10207. this.excludeWithLayerMask = 0;
  10208. // PBR Properties.
  10209. this.radius = 0.00001;
  10210. this._excludedMeshesIds = new Array();
  10211. this._includedOnlyMeshesIds = new Array();
  10212. scene.addLight(this);
  10213. }
  10214. /**
  10215. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10216. */
  10217. Light.prototype.toString = function (fullDetails) {
  10218. var ret = "Name: " + this.name;
  10219. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10220. if (this.animations) {
  10221. for (var i = 0; i < this.animations.length; i++) {
  10222. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10223. }
  10224. }
  10225. if (fullDetails) {
  10226. }
  10227. return ret;
  10228. };
  10229. Light.prototype.getShadowGenerator = function () {
  10230. return this._shadowGenerator;
  10231. };
  10232. Light.prototype.getAbsolutePosition = function () {
  10233. return BABYLON.Vector3.Zero();
  10234. };
  10235. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10236. };
  10237. Light.prototype._getWorldMatrix = function () {
  10238. return BABYLON.Matrix.Identity();
  10239. };
  10240. Light.prototype.canAffectMesh = function (mesh) {
  10241. if (!mesh) {
  10242. return true;
  10243. }
  10244. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10245. return false;
  10246. }
  10247. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10248. return false;
  10249. }
  10250. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10251. return false;
  10252. }
  10253. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10254. return false;
  10255. }
  10256. return true;
  10257. };
  10258. Light.prototype.getWorldMatrix = function () {
  10259. this._currentRenderId = this.getScene().getRenderId();
  10260. var worldMatrix = this._getWorldMatrix();
  10261. if (this.parent && this.parent.getWorldMatrix) {
  10262. if (!this._parentedWorldMatrix) {
  10263. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10264. }
  10265. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10266. this._markSyncedWithParent();
  10267. return this._parentedWorldMatrix;
  10268. }
  10269. return worldMatrix;
  10270. };
  10271. Light.prototype.dispose = function () {
  10272. if (this._shadowGenerator) {
  10273. this._shadowGenerator.dispose();
  10274. this._shadowGenerator = null;
  10275. }
  10276. // Animations
  10277. this.getScene().stopAnimation(this);
  10278. // Remove from scene
  10279. this.getScene().removeLight(this);
  10280. _super.prototype.dispose.call(this);
  10281. };
  10282. Light.prototype.getTypeID = function () {
  10283. return 0;
  10284. };
  10285. Light.prototype.clone = function (name) {
  10286. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10287. };
  10288. Light.prototype.serialize = function () {
  10289. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10290. // Type
  10291. serializationObject.type = this.getTypeID();
  10292. // Parent
  10293. if (this.parent) {
  10294. serializationObject.parentId = this.parent.id;
  10295. }
  10296. // Inclusion / exclusions
  10297. if (this.excludedMeshes.length > 0) {
  10298. serializationObject.excludedMeshesIds = [];
  10299. this.excludedMeshes.forEach(function (mesh) {
  10300. serializationObject.excludedMeshesIds.push(mesh.id);
  10301. });
  10302. }
  10303. if (this.includedOnlyMeshes.length > 0) {
  10304. serializationObject.includedOnlyMeshesIds = [];
  10305. this.includedOnlyMeshes.forEach(function (mesh) {
  10306. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10307. });
  10308. }
  10309. // Animations
  10310. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10311. serializationObject.ranges = this.serializeAnimationRanges();
  10312. return serializationObject;
  10313. };
  10314. Light.GetConstructorFromName = function (type, name, scene) {
  10315. switch (type) {
  10316. case 0:
  10317. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10318. case 1:
  10319. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10320. case 2:
  10321. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10322. case 3:
  10323. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10324. }
  10325. };
  10326. Light.Parse = function (parsedLight, scene) {
  10327. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10328. // Inclusion / exclusions
  10329. if (parsedLight.excludedMeshesIds) {
  10330. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10331. }
  10332. if (parsedLight.includedOnlyMeshesIds) {
  10333. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10334. }
  10335. // Parent
  10336. if (parsedLight.parentId) {
  10337. light._waitingParentId = parsedLight.parentId;
  10338. }
  10339. // Animations
  10340. if (parsedLight.animations) {
  10341. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10342. var parsedAnimation = parsedLight.animations[animationIndex];
  10343. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10344. }
  10345. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10346. }
  10347. if (parsedLight.autoAnimate) {
  10348. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10349. }
  10350. return light;
  10351. };
  10352. __decorate([
  10353. BABYLON.serializeAsColor3()
  10354. ], Light.prototype, "diffuse", void 0);
  10355. __decorate([
  10356. BABYLON.serializeAsColor3()
  10357. ], Light.prototype, "specular", void 0);
  10358. __decorate([
  10359. BABYLON.serialize()
  10360. ], Light.prototype, "intensity", void 0);
  10361. __decorate([
  10362. BABYLON.serialize()
  10363. ], Light.prototype, "range", void 0);
  10364. __decorate([
  10365. BABYLON.serialize()
  10366. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10367. __decorate([
  10368. BABYLON.serialize()
  10369. ], Light.prototype, "excludeWithLayerMask", void 0);
  10370. __decorate([
  10371. BABYLON.serialize()
  10372. ], Light.prototype, "radius", void 0);
  10373. return Light;
  10374. })(BABYLON.Node);
  10375. BABYLON.Light = Light;
  10376. })(BABYLON || (BABYLON = {}));
  10377. var BABYLON;
  10378. (function (BABYLON) {
  10379. var PointLight = (function (_super) {
  10380. __extends(PointLight, _super);
  10381. function PointLight(name, position, scene) {
  10382. _super.call(this, name, scene);
  10383. this.position = position;
  10384. }
  10385. PointLight.prototype.getAbsolutePosition = function () {
  10386. return this.transformedPosition ? this.transformedPosition : this.position;
  10387. };
  10388. PointLight.prototype.computeTransformedPosition = function () {
  10389. if (this.parent && this.parent.getWorldMatrix) {
  10390. if (!this.transformedPosition) {
  10391. this.transformedPosition = BABYLON.Vector3.Zero();
  10392. }
  10393. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10394. return true;
  10395. }
  10396. return false;
  10397. };
  10398. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10399. if (this.parent && this.parent.getWorldMatrix) {
  10400. this.computeTransformedPosition();
  10401. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10402. return;
  10403. }
  10404. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10405. };
  10406. PointLight.prototype.needCube = function () {
  10407. return true;
  10408. };
  10409. PointLight.prototype.supportsVSM = function () {
  10410. return false;
  10411. };
  10412. PointLight.prototype.needRefreshPerFrame = function () {
  10413. return false;
  10414. };
  10415. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10416. switch (faceIndex) {
  10417. case 0:
  10418. return new BABYLON.Vector3(1, 0, 0);
  10419. case 1:
  10420. return new BABYLON.Vector3(-1, 0, 0);
  10421. case 2:
  10422. return new BABYLON.Vector3(0, -1, 0);
  10423. case 3:
  10424. return new BABYLON.Vector3(0, 1, 0);
  10425. case 4:
  10426. return new BABYLON.Vector3(0, 0, 1);
  10427. case 5:
  10428. return new BABYLON.Vector3(0, 0, -1);
  10429. }
  10430. return BABYLON.Vector3.Zero();
  10431. };
  10432. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10433. var activeCamera = this.getScene().activeCamera;
  10434. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10435. };
  10436. PointLight.prototype._getWorldMatrix = function () {
  10437. if (!this._worldMatrix) {
  10438. this._worldMatrix = BABYLON.Matrix.Identity();
  10439. }
  10440. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10441. return this._worldMatrix;
  10442. };
  10443. PointLight.prototype.getTypeID = function () {
  10444. return 0;
  10445. };
  10446. __decorate([
  10447. BABYLON.serializeAsVector3()
  10448. ], PointLight.prototype, "position", void 0);
  10449. return PointLight;
  10450. })(BABYLON.Light);
  10451. BABYLON.PointLight = PointLight;
  10452. })(BABYLON || (BABYLON = {}));
  10453. var BABYLON;
  10454. (function (BABYLON) {
  10455. var SpotLight = (function (_super) {
  10456. __extends(SpotLight, _super);
  10457. function SpotLight(name, position, direction, angle, exponent, scene) {
  10458. _super.call(this, name, scene);
  10459. this.position = position;
  10460. this.direction = direction;
  10461. this.angle = angle;
  10462. this.exponent = exponent;
  10463. }
  10464. SpotLight.prototype.getAbsolutePosition = function () {
  10465. return this.transformedPosition ? this.transformedPosition : this.position;
  10466. };
  10467. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10468. var activeCamera = this.getScene().activeCamera;
  10469. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10470. };
  10471. SpotLight.prototype.needCube = function () {
  10472. return false;
  10473. };
  10474. SpotLight.prototype.supportsVSM = function () {
  10475. return true;
  10476. };
  10477. SpotLight.prototype.needRefreshPerFrame = function () {
  10478. return false;
  10479. };
  10480. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10481. return this.direction;
  10482. };
  10483. SpotLight.prototype.setDirectionToTarget = function (target) {
  10484. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10485. return this.direction;
  10486. };
  10487. SpotLight.prototype.computeTransformedPosition = function () {
  10488. if (this.parent && this.parent.getWorldMatrix) {
  10489. if (!this.transformedPosition) {
  10490. this.transformedPosition = BABYLON.Vector3.Zero();
  10491. }
  10492. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10493. return true;
  10494. }
  10495. return false;
  10496. };
  10497. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10498. var normalizeDirection;
  10499. if (this.parent && this.parent.getWorldMatrix) {
  10500. if (!this._transformedDirection) {
  10501. this._transformedDirection = BABYLON.Vector3.Zero();
  10502. }
  10503. this.computeTransformedPosition();
  10504. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10505. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10506. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10507. }
  10508. else {
  10509. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10510. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10511. }
  10512. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10513. };
  10514. SpotLight.prototype._getWorldMatrix = function () {
  10515. if (!this._worldMatrix) {
  10516. this._worldMatrix = BABYLON.Matrix.Identity();
  10517. }
  10518. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10519. return this._worldMatrix;
  10520. };
  10521. SpotLight.prototype.getTypeID = function () {
  10522. return 2;
  10523. };
  10524. __decorate([
  10525. BABYLON.serializeAsVector3()
  10526. ], SpotLight.prototype, "position", void 0);
  10527. __decorate([
  10528. BABYLON.serializeAsVector3()
  10529. ], SpotLight.prototype, "direction", void 0);
  10530. __decorate([
  10531. BABYLON.serialize()
  10532. ], SpotLight.prototype, "angle", void 0);
  10533. __decorate([
  10534. BABYLON.serialize()
  10535. ], SpotLight.prototype, "exponent", void 0);
  10536. return SpotLight;
  10537. })(BABYLON.Light);
  10538. BABYLON.SpotLight = SpotLight;
  10539. })(BABYLON || (BABYLON = {}));
  10540. var BABYLON;
  10541. (function (BABYLON) {
  10542. var HemisphericLight = (function (_super) {
  10543. __extends(HemisphericLight, _super);
  10544. function HemisphericLight(name, direction, scene) {
  10545. _super.call(this, name, scene);
  10546. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10547. this.direction = direction;
  10548. }
  10549. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10550. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10551. return this.direction;
  10552. };
  10553. HemisphericLight.prototype.getShadowGenerator = function () {
  10554. return null;
  10555. };
  10556. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10557. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10558. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10559. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10560. };
  10561. HemisphericLight.prototype._getWorldMatrix = function () {
  10562. if (!this._worldMatrix) {
  10563. this._worldMatrix = BABYLON.Matrix.Identity();
  10564. }
  10565. return this._worldMatrix;
  10566. };
  10567. HemisphericLight.prototype.getTypeID = function () {
  10568. return 3;
  10569. };
  10570. __decorate([
  10571. BABYLON.serializeAsColor3()
  10572. ], HemisphericLight.prototype, "groundColor", void 0);
  10573. __decorate([
  10574. BABYLON.serializeAsVector3()
  10575. ], HemisphericLight.prototype, "direction", void 0);
  10576. return HemisphericLight;
  10577. })(BABYLON.Light);
  10578. BABYLON.HemisphericLight = HemisphericLight;
  10579. })(BABYLON || (BABYLON = {}));
  10580. var BABYLON;
  10581. (function (BABYLON) {
  10582. var DirectionalLight = (function (_super) {
  10583. __extends(DirectionalLight, _super);
  10584. function DirectionalLight(name, direction, scene) {
  10585. _super.call(this, name, scene);
  10586. this.shadowOrthoScale = 0.5;
  10587. this.autoUpdateExtends = true;
  10588. // Cache
  10589. this._orthoLeft = Number.MAX_VALUE;
  10590. this._orthoRight = Number.MIN_VALUE;
  10591. this._orthoTop = Number.MIN_VALUE;
  10592. this._orthoBottom = Number.MAX_VALUE;
  10593. this.position = direction.scale(-1);
  10594. this.direction = direction;
  10595. }
  10596. DirectionalLight.prototype.getAbsolutePosition = function () {
  10597. return this.transformedPosition ? this.transformedPosition : this.position;
  10598. };
  10599. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10600. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10601. return this.direction;
  10602. };
  10603. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10604. var activeCamera = this.getScene().activeCamera;
  10605. // Check extends
  10606. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10607. var tempVector3 = BABYLON.Vector3.Zero();
  10608. this._orthoLeft = Number.MAX_VALUE;
  10609. this._orthoRight = Number.MIN_VALUE;
  10610. this._orthoTop = Number.MIN_VALUE;
  10611. this._orthoBottom = Number.MAX_VALUE;
  10612. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10613. var mesh = renderList[meshIndex];
  10614. if (!mesh) {
  10615. continue;
  10616. }
  10617. var boundingInfo = mesh.getBoundingInfo();
  10618. if (!boundingInfo) {
  10619. continue;
  10620. }
  10621. var boundingBox = boundingInfo.boundingBox;
  10622. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10623. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10624. if (tempVector3.x < this._orthoLeft)
  10625. this._orthoLeft = tempVector3.x;
  10626. if (tempVector3.y < this._orthoBottom)
  10627. this._orthoBottom = tempVector3.y;
  10628. if (tempVector3.x > this._orthoRight)
  10629. this._orthoRight = tempVector3.x;
  10630. if (tempVector3.y > this._orthoTop)
  10631. this._orthoTop = tempVector3.y;
  10632. }
  10633. }
  10634. }
  10635. var xOffset = this._orthoRight - this._orthoLeft;
  10636. var yOffset = this._orthoTop - this._orthoBottom;
  10637. 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);
  10638. };
  10639. DirectionalLight.prototype.supportsVSM = function () {
  10640. return true;
  10641. };
  10642. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10643. return true;
  10644. };
  10645. DirectionalLight.prototype.needCube = function () {
  10646. return false;
  10647. };
  10648. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10649. return this.direction;
  10650. };
  10651. DirectionalLight.prototype.computeTransformedPosition = function () {
  10652. if (this.parent && this.parent.getWorldMatrix) {
  10653. if (!this.transformedPosition) {
  10654. this.transformedPosition = BABYLON.Vector3.Zero();
  10655. }
  10656. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10657. return true;
  10658. }
  10659. return false;
  10660. };
  10661. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10662. if (this.parent && this.parent.getWorldMatrix) {
  10663. if (!this._transformedDirection) {
  10664. this._transformedDirection = BABYLON.Vector3.Zero();
  10665. }
  10666. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10667. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10668. return;
  10669. }
  10670. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10671. };
  10672. DirectionalLight.prototype._getWorldMatrix = function () {
  10673. if (!this._worldMatrix) {
  10674. this._worldMatrix = BABYLON.Matrix.Identity();
  10675. }
  10676. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10677. return this._worldMatrix;
  10678. };
  10679. DirectionalLight.prototype.getTypeID = function () {
  10680. return 1;
  10681. };
  10682. __decorate([
  10683. BABYLON.serializeAsVector3()
  10684. ], DirectionalLight.prototype, "position", void 0);
  10685. __decorate([
  10686. BABYLON.serializeAsVector3()
  10687. ], DirectionalLight.prototype, "direction", void 0);
  10688. __decorate([
  10689. BABYLON.serialize()
  10690. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10691. __decorate([
  10692. BABYLON.serialize()
  10693. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10694. return DirectionalLight;
  10695. })(BABYLON.Light);
  10696. BABYLON.DirectionalLight = DirectionalLight;
  10697. })(BABYLON || (BABYLON = {}));
  10698. var BABYLON;
  10699. (function (BABYLON) {
  10700. var ShadowGenerator = (function () {
  10701. function ShadowGenerator(mapSize, light) {
  10702. var _this = this;
  10703. // Members
  10704. this._filter = ShadowGenerator.FILTER_NONE;
  10705. this.blurScale = 2;
  10706. this._blurBoxOffset = 0;
  10707. this._bias = 0.00005;
  10708. this._lightDirection = BABYLON.Vector3.Zero();
  10709. this.forceBackFacesOnly = false;
  10710. this._darkness = 0;
  10711. this._transparencyShadow = false;
  10712. this._viewMatrix = BABYLON.Matrix.Zero();
  10713. this._projectionMatrix = BABYLON.Matrix.Zero();
  10714. this._transformMatrix = BABYLON.Matrix.Zero();
  10715. this._worldViewProjection = BABYLON.Matrix.Zero();
  10716. this._currentFaceIndex = 0;
  10717. this._currentFaceIndexCache = 0;
  10718. this._light = light;
  10719. this._scene = light.getScene();
  10720. this._mapSize = mapSize;
  10721. light._shadowGenerator = this;
  10722. // Render target
  10723. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10724. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10725. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10726. this._shadowMap.anisotropicFilteringLevel = 1;
  10727. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10728. this._shadowMap.renderParticles = false;
  10729. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10730. _this._currentFaceIndex = faceIndex;
  10731. });
  10732. this._shadowMap.onAfterUnbindObservable.add(function () {
  10733. if (!_this.useBlurVarianceShadowMap) {
  10734. return;
  10735. }
  10736. if (!_this._shadowMap2) {
  10737. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10738. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10739. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10740. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10741. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10742. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10743. effect.setTexture("textureSampler", _this._shadowMap);
  10744. });
  10745. _this.blurBoxOffset = 1;
  10746. }
  10747. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10748. });
  10749. // Custom render function
  10750. var renderSubMesh = function (subMesh) {
  10751. var mesh = subMesh.getRenderingMesh();
  10752. var scene = _this._scene;
  10753. var engine = scene.getEngine();
  10754. // Culling
  10755. engine.setState(subMesh.getMaterial().backFaceCulling);
  10756. // Managing instances
  10757. var batch = mesh._getInstancesRenderList(subMesh._id);
  10758. if (batch.mustReturn) {
  10759. return;
  10760. }
  10761. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10762. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10763. engine.enableEffect(_this._effect);
  10764. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10765. var material = subMesh.getMaterial();
  10766. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10767. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10768. if (_this.getLight().needCube()) {
  10769. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10770. }
  10771. // Alpha test
  10772. if (material && material.needAlphaTesting()) {
  10773. var alphaTexture = material.getAlphaTestTexture();
  10774. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10775. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10776. }
  10777. // Bones
  10778. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10779. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10780. }
  10781. if (_this.forceBackFacesOnly) {
  10782. engine.setState(true, 0, false, true);
  10783. }
  10784. // Draw
  10785. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10786. if (_this.forceBackFacesOnly) {
  10787. engine.setState(true, 0, false, false);
  10788. }
  10789. }
  10790. else {
  10791. // Need to reset refresh rate of the shadowMap
  10792. _this._shadowMap.resetRefreshCounter();
  10793. }
  10794. };
  10795. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10796. var index;
  10797. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10798. renderSubMesh(opaqueSubMeshes.data[index]);
  10799. }
  10800. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10801. renderSubMesh(alphaTestSubMeshes.data[index]);
  10802. }
  10803. if (_this._transparencyShadow) {
  10804. for (index = 0; index < transparentSubMeshes.length; index++) {
  10805. renderSubMesh(transparentSubMeshes.data[index]);
  10806. }
  10807. }
  10808. };
  10809. this._shadowMap.onClearObservable.add(function (engine) {
  10810. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10811. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10812. }
  10813. else {
  10814. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10815. }
  10816. });
  10817. }
  10818. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10819. // Static
  10820. get: function () {
  10821. return ShadowGenerator._FILTER_NONE;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10827. get: function () {
  10828. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10834. get: function () {
  10835. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10841. get: function () {
  10842. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10848. get: function () {
  10849. return this._bias;
  10850. },
  10851. set: function (bias) {
  10852. this._bias = bias;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10858. get: function () {
  10859. return this._blurBoxOffset;
  10860. },
  10861. set: function (value) {
  10862. var _this = this;
  10863. if (this._blurBoxOffset === value) {
  10864. return;
  10865. }
  10866. this._blurBoxOffset = value;
  10867. if (this._boxBlurPostprocess) {
  10868. this._boxBlurPostprocess.dispose();
  10869. }
  10870. 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);
  10871. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10872. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10873. });
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10879. get: function () {
  10880. return this._filter;
  10881. },
  10882. set: function (value) {
  10883. if (this._filter === value) {
  10884. return;
  10885. }
  10886. this._filter = value;
  10887. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10888. this._shadowMap.anisotropicFilteringLevel = 16;
  10889. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10890. }
  10891. else {
  10892. this._shadowMap.anisotropicFilteringLevel = 1;
  10893. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10894. }
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10900. get: function () {
  10901. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10902. },
  10903. set: function (value) {
  10904. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10910. get: function () {
  10911. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10912. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10913. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10914. },
  10915. set: function (value) {
  10916. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10922. get: function () {
  10923. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10924. },
  10925. set: function (value) {
  10926. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10927. },
  10928. enumerable: true,
  10929. configurable: true
  10930. });
  10931. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10932. var defines = [];
  10933. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10934. defines.push("#define VSM");
  10935. }
  10936. if (this.getLight().needCube()) {
  10937. defines.push("#define CUBEMAP");
  10938. }
  10939. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10940. var mesh = subMesh.getMesh();
  10941. var material = subMesh.getMaterial();
  10942. // Alpha test
  10943. if (material && material.needAlphaTesting()) {
  10944. defines.push("#define ALPHATEST");
  10945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10946. attribs.push(BABYLON.VertexBuffer.UVKind);
  10947. defines.push("#define UV1");
  10948. }
  10949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10950. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10951. defines.push("#define UV2");
  10952. }
  10953. }
  10954. // Bones
  10955. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10956. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10957. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10958. if (mesh.numBoneInfluencers > 4) {
  10959. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10960. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10961. }
  10962. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10963. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10964. }
  10965. else {
  10966. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10967. }
  10968. // Instances
  10969. if (useInstances) {
  10970. defines.push("#define INSTANCES");
  10971. attribs.push("world0");
  10972. attribs.push("world1");
  10973. attribs.push("world2");
  10974. attribs.push("world3");
  10975. }
  10976. // Get correct effect
  10977. var join = defines.join("\n");
  10978. if (this._cachedDefines !== join) {
  10979. this._cachedDefines = join;
  10980. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10981. }
  10982. return this._effect.isReady();
  10983. };
  10984. ShadowGenerator.prototype.getShadowMap = function () {
  10985. return this._shadowMap;
  10986. };
  10987. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10988. if (this._shadowMap2) {
  10989. return this._shadowMap2;
  10990. }
  10991. return this._shadowMap;
  10992. };
  10993. ShadowGenerator.prototype.getLight = function () {
  10994. return this._light;
  10995. };
  10996. // Methods
  10997. ShadowGenerator.prototype.getTransformMatrix = function () {
  10998. var scene = this._scene;
  10999. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11000. return this._transformMatrix;
  11001. }
  11002. this._currentRenderID = scene.getRenderId();
  11003. this._currentFaceIndexCache = this._currentFaceIndex;
  11004. var lightPosition = this._light.position;
  11005. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11006. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11007. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11008. }
  11009. if (this._light.computeTransformedPosition()) {
  11010. lightPosition = this._light.transformedPosition;
  11011. }
  11012. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11013. this._cachedPosition = lightPosition.clone();
  11014. this._cachedDirection = this._lightDirection.clone();
  11015. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11016. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11017. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11018. }
  11019. return this._transformMatrix;
  11020. };
  11021. ShadowGenerator.prototype.getDarkness = function () {
  11022. return this._darkness;
  11023. };
  11024. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11025. if (darkness >= 1.0)
  11026. this._darkness = 1.0;
  11027. else if (darkness <= 0.0)
  11028. this._darkness = 0.0;
  11029. else
  11030. this._darkness = darkness;
  11031. };
  11032. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11033. this._transparencyShadow = hasShadow;
  11034. };
  11035. ShadowGenerator.prototype._packHalf = function (depth) {
  11036. var scale = depth * 255.0;
  11037. var fract = scale - Math.floor(scale);
  11038. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11039. };
  11040. ShadowGenerator.prototype.dispose = function () {
  11041. this._shadowMap.dispose();
  11042. if (this._shadowMap2) {
  11043. this._shadowMap2.dispose();
  11044. }
  11045. if (this._downSamplePostprocess) {
  11046. this._downSamplePostprocess.dispose();
  11047. }
  11048. if (this._boxBlurPostprocess) {
  11049. this._boxBlurPostprocess.dispose();
  11050. }
  11051. };
  11052. ShadowGenerator.prototype.serialize = function () {
  11053. var serializationObject = {};
  11054. serializationObject.lightId = this._light.id;
  11055. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11056. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11057. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11058. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11059. serializationObject.renderList = [];
  11060. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11061. var mesh = this.getShadowMap().renderList[meshIndex];
  11062. serializationObject.renderList.push(mesh.id);
  11063. }
  11064. return serializationObject;
  11065. };
  11066. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11067. //casting to point light, as light is missing the position attr and typescript complains.
  11068. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11069. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11070. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11071. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11072. meshes.forEach(function (mesh) {
  11073. shadowGenerator.getShadowMap().renderList.push(mesh);
  11074. });
  11075. }
  11076. if (parsedShadowGenerator.usePoissonSampling) {
  11077. shadowGenerator.usePoissonSampling = true;
  11078. }
  11079. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11080. shadowGenerator.useVarianceShadowMap = true;
  11081. }
  11082. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11083. shadowGenerator.useBlurVarianceShadowMap = true;
  11084. if (parsedShadowGenerator.blurScale) {
  11085. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11086. }
  11087. if (parsedShadowGenerator.blurBoxOffset) {
  11088. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11089. }
  11090. }
  11091. if (parsedShadowGenerator.bias !== undefined) {
  11092. shadowGenerator.bias = parsedShadowGenerator.bias;
  11093. }
  11094. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11095. return shadowGenerator;
  11096. };
  11097. ShadowGenerator._FILTER_NONE = 0;
  11098. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11099. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11100. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11101. return ShadowGenerator;
  11102. })();
  11103. BABYLON.ShadowGenerator = ShadowGenerator;
  11104. })(BABYLON || (BABYLON = {}));
  11105. var BABYLON;
  11106. (function (BABYLON) {
  11107. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11108. if (boxMin.x > sphereCenter.x + sphereRadius)
  11109. return false;
  11110. if (sphereCenter.x - sphereRadius > boxMax.x)
  11111. return false;
  11112. if (boxMin.y > sphereCenter.y + sphereRadius)
  11113. return false;
  11114. if (sphereCenter.y - sphereRadius > boxMax.y)
  11115. return false;
  11116. if (boxMin.z > sphereCenter.z + sphereRadius)
  11117. return false;
  11118. if (sphereCenter.z - sphereRadius > boxMax.z)
  11119. return false;
  11120. return true;
  11121. };
  11122. var getLowestRoot = (function () {
  11123. var result = { root: 0, found: false };
  11124. return function (a, b, c, maxR) {
  11125. result.root = 0;
  11126. result.found = false;
  11127. var determinant = b * b - 4.0 * a * c;
  11128. if (determinant < 0)
  11129. return result;
  11130. var sqrtD = Math.sqrt(determinant);
  11131. var r1 = (-b - sqrtD) / (2.0 * a);
  11132. var r2 = (-b + sqrtD) / (2.0 * a);
  11133. if (r1 > r2) {
  11134. var temp = r2;
  11135. r2 = r1;
  11136. r1 = temp;
  11137. }
  11138. if (r1 > 0 && r1 < maxR) {
  11139. result.root = r1;
  11140. result.found = true;
  11141. return result;
  11142. }
  11143. if (r2 > 0 && r2 < maxR) {
  11144. result.root = r2;
  11145. result.found = true;
  11146. return result;
  11147. }
  11148. return result;
  11149. };
  11150. })();
  11151. var Collider = (function () {
  11152. function Collider() {
  11153. this.radius = new BABYLON.Vector3(1, 1, 1);
  11154. this.retry = 0;
  11155. this.basePointWorld = BABYLON.Vector3.Zero();
  11156. this.velocityWorld = BABYLON.Vector3.Zero();
  11157. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11158. this._collisionPoint = BABYLON.Vector3.Zero();
  11159. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11160. this._tempVector = BABYLON.Vector3.Zero();
  11161. this._tempVector2 = BABYLON.Vector3.Zero();
  11162. this._tempVector3 = BABYLON.Vector3.Zero();
  11163. this._tempVector4 = BABYLON.Vector3.Zero();
  11164. this._edge = BABYLON.Vector3.Zero();
  11165. this._baseToVertex = BABYLON.Vector3.Zero();
  11166. this._destinationPoint = BABYLON.Vector3.Zero();
  11167. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11168. this._displacementVector = BABYLON.Vector3.Zero();
  11169. }
  11170. // Methods
  11171. Collider.prototype._initialize = function (source, dir, e) {
  11172. this.velocity = dir;
  11173. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11174. this.basePoint = source;
  11175. source.multiplyToRef(this.radius, this.basePointWorld);
  11176. dir.multiplyToRef(this.radius, this.velocityWorld);
  11177. this.velocityWorldLength = this.velocityWorld.length();
  11178. this.epsilon = e;
  11179. this.collisionFound = false;
  11180. };
  11181. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11182. pa.subtractToRef(point, this._tempVector);
  11183. pb.subtractToRef(point, this._tempVector2);
  11184. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11185. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11186. if (d < 0)
  11187. return false;
  11188. pc.subtractToRef(point, this._tempVector3);
  11189. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11190. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11191. if (d < 0)
  11192. return false;
  11193. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11194. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11195. return d >= 0;
  11196. };
  11197. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11198. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11199. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11200. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11201. return false;
  11202. }
  11203. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11204. return false;
  11205. return true;
  11206. };
  11207. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11208. var t0;
  11209. var embeddedInPlane = false;
  11210. //defensive programming, actually not needed.
  11211. if (!trianglePlaneArray) {
  11212. trianglePlaneArray = [];
  11213. }
  11214. if (!trianglePlaneArray[faceIndex]) {
  11215. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11216. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11217. }
  11218. var trianglePlane = trianglePlaneArray[faceIndex];
  11219. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11220. return;
  11221. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11222. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11223. if (normalDotVelocity == 0) {
  11224. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11225. return;
  11226. embeddedInPlane = true;
  11227. t0 = 0;
  11228. }
  11229. else {
  11230. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11231. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11232. if (t0 > t1) {
  11233. var temp = t1;
  11234. t1 = t0;
  11235. t0 = temp;
  11236. }
  11237. if (t0 > 1.0 || t1 < 0.0)
  11238. return;
  11239. if (t0 < 0)
  11240. t0 = 0;
  11241. if (t0 > 1.0)
  11242. t0 = 1.0;
  11243. }
  11244. this._collisionPoint.copyFromFloats(0, 0, 0);
  11245. var found = false;
  11246. var t = 1.0;
  11247. if (!embeddedInPlane) {
  11248. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11249. this.velocity.scaleToRef(t0, this._tempVector);
  11250. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11251. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11252. found = true;
  11253. t = t0;
  11254. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11255. }
  11256. }
  11257. if (!found) {
  11258. var velocitySquaredLength = this.velocity.lengthSquared();
  11259. var a = velocitySquaredLength;
  11260. this.basePoint.subtractToRef(p1, this._tempVector);
  11261. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11262. var c = this._tempVector.lengthSquared() - 1.0;
  11263. var lowestRoot = getLowestRoot(a, b, c, t);
  11264. if (lowestRoot.found) {
  11265. t = lowestRoot.root;
  11266. found = true;
  11267. this._collisionPoint.copyFrom(p1);
  11268. }
  11269. this.basePoint.subtractToRef(p2, this._tempVector);
  11270. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11271. c = this._tempVector.lengthSquared() - 1.0;
  11272. lowestRoot = getLowestRoot(a, b, c, t);
  11273. if (lowestRoot.found) {
  11274. t = lowestRoot.root;
  11275. found = true;
  11276. this._collisionPoint.copyFrom(p2);
  11277. }
  11278. this.basePoint.subtractToRef(p3, this._tempVector);
  11279. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11280. c = this._tempVector.lengthSquared() - 1.0;
  11281. lowestRoot = getLowestRoot(a, b, c, t);
  11282. if (lowestRoot.found) {
  11283. t = lowestRoot.root;
  11284. found = true;
  11285. this._collisionPoint.copyFrom(p3);
  11286. }
  11287. p2.subtractToRef(p1, this._edge);
  11288. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11289. var edgeSquaredLength = this._edge.lengthSquared();
  11290. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11291. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11292. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11293. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11294. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11295. lowestRoot = getLowestRoot(a, b, c, t);
  11296. if (lowestRoot.found) {
  11297. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11298. if (f >= 0.0 && f <= 1.0) {
  11299. t = lowestRoot.root;
  11300. found = true;
  11301. this._edge.scaleInPlace(f);
  11302. p1.addToRef(this._edge, this._collisionPoint);
  11303. }
  11304. }
  11305. p3.subtractToRef(p2, this._edge);
  11306. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11307. edgeSquaredLength = this._edge.lengthSquared();
  11308. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11309. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11310. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11311. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11312. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11313. lowestRoot = getLowestRoot(a, b, c, t);
  11314. if (lowestRoot.found) {
  11315. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11316. if (f >= 0.0 && f <= 1.0) {
  11317. t = lowestRoot.root;
  11318. found = true;
  11319. this._edge.scaleInPlace(f);
  11320. p2.addToRef(this._edge, this._collisionPoint);
  11321. }
  11322. }
  11323. p1.subtractToRef(p3, this._edge);
  11324. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11325. edgeSquaredLength = this._edge.lengthSquared();
  11326. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11327. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11328. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11329. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11330. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11331. lowestRoot = getLowestRoot(a, b, c, t);
  11332. if (lowestRoot.found) {
  11333. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11334. if (f >= 0.0 && f <= 1.0) {
  11335. t = lowestRoot.root;
  11336. found = true;
  11337. this._edge.scaleInPlace(f);
  11338. p3.addToRef(this._edge, this._collisionPoint);
  11339. }
  11340. }
  11341. }
  11342. if (found) {
  11343. var distToCollision = t * this.velocity.length();
  11344. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11345. if (!this.intersectionPoint) {
  11346. this.intersectionPoint = this._collisionPoint.clone();
  11347. }
  11348. else {
  11349. this.intersectionPoint.copyFrom(this._collisionPoint);
  11350. }
  11351. this.nearestDistance = distToCollision;
  11352. this.collisionFound = true;
  11353. }
  11354. }
  11355. };
  11356. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11357. for (var i = indexStart; i < indexEnd; i += 3) {
  11358. var p1 = pts[indices[i] - decal];
  11359. var p2 = pts[indices[i + 1] - decal];
  11360. var p3 = pts[indices[i + 2] - decal];
  11361. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11362. }
  11363. };
  11364. Collider.prototype._getResponse = function (pos, vel) {
  11365. pos.addToRef(vel, this._destinationPoint);
  11366. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11367. this.basePoint.addToRef(vel, pos);
  11368. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11369. this._slidePlaneNormal.normalize();
  11370. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11371. pos.addInPlace(this._displacementVector);
  11372. this.intersectionPoint.addInPlace(this._displacementVector);
  11373. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11374. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11375. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11376. };
  11377. return Collider;
  11378. })();
  11379. BABYLON.Collider = Collider;
  11380. })(BABYLON || (BABYLON = {}));
  11381. var BABYLON;
  11382. (function (BABYLON) {
  11383. //WebWorker code will be inserted to this variable.
  11384. BABYLON.CollisionWorker = "";
  11385. (function (WorkerTaskType) {
  11386. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11387. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11388. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11389. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11390. var WorkerTaskType = BABYLON.WorkerTaskType;
  11391. (function (WorkerReplyType) {
  11392. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11393. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11394. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11395. var WorkerReplyType = BABYLON.WorkerReplyType;
  11396. var CollisionCoordinatorWorker = (function () {
  11397. function CollisionCoordinatorWorker() {
  11398. var _this = this;
  11399. this._scaledPosition = BABYLON.Vector3.Zero();
  11400. this._scaledVelocity = BABYLON.Vector3.Zero();
  11401. this.onMeshUpdated = function (mesh) {
  11402. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11403. };
  11404. this.onGeometryUpdated = function (geometry) {
  11405. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11406. };
  11407. this._afterRender = function () {
  11408. if (!_this._init)
  11409. return;
  11410. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11411. return;
  11412. }
  11413. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11414. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11415. if (_this._runningUpdated > 4) {
  11416. return;
  11417. }
  11418. ++_this._runningUpdated;
  11419. var payload = {
  11420. updatedMeshes: _this._addUpdateMeshesList,
  11421. updatedGeometries: _this._addUpdateGeometriesList,
  11422. removedGeometries: _this._toRemoveGeometryArray,
  11423. removedMeshes: _this._toRemoveMeshesArray
  11424. };
  11425. var message = {
  11426. payload: payload,
  11427. taskType: WorkerTaskType.UPDATE
  11428. };
  11429. var serializable = [];
  11430. for (var id in payload.updatedGeometries) {
  11431. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11432. //prepare transferables
  11433. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11434. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11435. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11436. }
  11437. }
  11438. _this._worker.postMessage(message, serializable);
  11439. _this._addUpdateMeshesList = {};
  11440. _this._addUpdateGeometriesList = {};
  11441. _this._toRemoveGeometryArray = [];
  11442. _this._toRemoveMeshesArray = [];
  11443. };
  11444. this._onMessageFromWorker = function (e) {
  11445. var returnData = e.data;
  11446. if (returnData.error != WorkerReplyType.SUCCESS) {
  11447. //TODO what errors can be returned from the worker?
  11448. BABYLON.Tools.Warn("error returned from worker!");
  11449. return;
  11450. }
  11451. switch (returnData.taskType) {
  11452. case WorkerTaskType.INIT:
  11453. _this._init = true;
  11454. //Update the worked with ALL of the scene's current state
  11455. _this._scene.meshes.forEach(function (mesh) {
  11456. _this.onMeshAdded(mesh);
  11457. });
  11458. _this._scene.getGeometries().forEach(function (geometry) {
  11459. _this.onGeometryAdded(geometry);
  11460. });
  11461. break;
  11462. case WorkerTaskType.UPDATE:
  11463. _this._runningUpdated--;
  11464. break;
  11465. case WorkerTaskType.COLLIDE:
  11466. _this._runningCollisionTask = false;
  11467. var returnPayload = returnData.payload;
  11468. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11469. return;
  11470. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11471. //cleanup
  11472. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11473. break;
  11474. }
  11475. };
  11476. this._collisionsCallbackArray = [];
  11477. this._init = false;
  11478. this._runningUpdated = 0;
  11479. this._runningCollisionTask = false;
  11480. this._addUpdateMeshesList = {};
  11481. this._addUpdateGeometriesList = {};
  11482. this._toRemoveGeometryArray = [];
  11483. this._toRemoveMeshesArray = [];
  11484. }
  11485. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11486. if (!this._init)
  11487. return;
  11488. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11489. return;
  11490. position.divideToRef(collider.radius, this._scaledPosition);
  11491. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11492. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11493. var payload = {
  11494. collider: {
  11495. position: this._scaledPosition.asArray(),
  11496. velocity: this._scaledVelocity.asArray(),
  11497. radius: collider.radius.asArray()
  11498. },
  11499. collisionId: collisionIndex,
  11500. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11501. maximumRetry: maximumRetry
  11502. };
  11503. var message = {
  11504. payload: payload,
  11505. taskType: WorkerTaskType.COLLIDE
  11506. };
  11507. this._worker.postMessage(message);
  11508. };
  11509. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11510. this._scene = scene;
  11511. this._scene.registerAfterRender(this._afterRender);
  11512. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11513. this._worker = new Worker(workerUrl);
  11514. this._worker.onmessage = this._onMessageFromWorker;
  11515. var message = {
  11516. payload: {},
  11517. taskType: WorkerTaskType.INIT
  11518. };
  11519. this._worker.postMessage(message);
  11520. };
  11521. CollisionCoordinatorWorker.prototype.destroy = function () {
  11522. this._scene.unregisterAfterRender(this._afterRender);
  11523. this._worker.terminate();
  11524. };
  11525. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11526. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11527. this.onMeshUpdated(mesh);
  11528. };
  11529. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11530. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11531. };
  11532. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11533. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11534. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11535. this.onGeometryUpdated(geometry);
  11536. };
  11537. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11538. this._toRemoveGeometryArray.push(geometry.id);
  11539. };
  11540. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11541. var submeshes = [];
  11542. if (mesh.subMeshes) {
  11543. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11544. return {
  11545. position: idx,
  11546. verticesStart: sm.verticesStart,
  11547. verticesCount: sm.verticesCount,
  11548. indexStart: sm.indexStart,
  11549. indexCount: sm.indexCount,
  11550. hasMaterial: !!sm.getMaterial(),
  11551. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11552. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11553. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11554. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11555. };
  11556. });
  11557. }
  11558. var geometryId = null;
  11559. if (mesh instanceof BABYLON.Mesh) {
  11560. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11561. }
  11562. else if (mesh instanceof BABYLON.InstancedMesh) {
  11563. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11564. }
  11565. return {
  11566. uniqueId: mesh.uniqueId,
  11567. id: mesh.id,
  11568. name: mesh.name,
  11569. geometryId: geometryId,
  11570. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11571. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11572. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11573. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11574. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11575. subMeshes: submeshes,
  11576. checkCollisions: mesh.checkCollisions
  11577. };
  11578. };
  11579. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11580. return {
  11581. id: geometry.id,
  11582. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11583. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11584. indices: new Int32Array(geometry.getIndices() || []),
  11585. };
  11586. };
  11587. return CollisionCoordinatorWorker;
  11588. })();
  11589. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11590. var CollisionCoordinatorLegacy = (function () {
  11591. function CollisionCoordinatorLegacy() {
  11592. this._scaledPosition = BABYLON.Vector3.Zero();
  11593. this._scaledVelocity = BABYLON.Vector3.Zero();
  11594. this._finalPosition = BABYLON.Vector3.Zero();
  11595. }
  11596. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11597. position.divideToRef(collider.radius, this._scaledPosition);
  11598. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11599. collider.collidedMesh = null;
  11600. collider.retry = 0;
  11601. collider.initialVelocity = this._scaledVelocity;
  11602. collider.initialPosition = this._scaledPosition;
  11603. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11604. this._finalPosition.multiplyInPlace(collider.radius);
  11605. //run the callback
  11606. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11607. };
  11608. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11609. this._scene = scene;
  11610. };
  11611. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11612. //Legacy need no destruction method.
  11613. };
  11614. //No update in legacy mode
  11615. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11616. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11617. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11618. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11619. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11620. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11621. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11622. if (excludedMesh === void 0) { excludedMesh = null; }
  11623. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11624. if (collider.retry >= maximumRetry) {
  11625. finalPosition.copyFrom(position);
  11626. return;
  11627. }
  11628. collider._initialize(position, velocity, closeDistance);
  11629. // Check all meshes
  11630. for (var index = 0; index < this._scene.meshes.length; index++) {
  11631. var mesh = this._scene.meshes[index];
  11632. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11633. mesh._checkCollision(collider);
  11634. }
  11635. }
  11636. if (!collider.collisionFound) {
  11637. position.addToRef(velocity, finalPosition);
  11638. return;
  11639. }
  11640. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11641. collider._getResponse(position, velocity);
  11642. }
  11643. if (velocity.length() <= closeDistance) {
  11644. finalPosition.copyFrom(position);
  11645. return;
  11646. }
  11647. collider.retry++;
  11648. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11649. };
  11650. return CollisionCoordinatorLegacy;
  11651. })();
  11652. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11653. })(BABYLON || (BABYLON = {}));
  11654. var BABYLON;
  11655. (function (BABYLON) {
  11656. var Camera = (function (_super) {
  11657. __extends(Camera, _super);
  11658. function Camera(name, position, scene) {
  11659. _super.call(this, name, scene);
  11660. this.upVector = BABYLON.Vector3.Up();
  11661. this.orthoLeft = null;
  11662. this.orthoRight = null;
  11663. this.orthoBottom = null;
  11664. this.orthoTop = null;
  11665. this.fov = 0.8;
  11666. this.minZ = 1.0;
  11667. this.maxZ = 10000.0;
  11668. this.inertia = 0.9;
  11669. this.mode = Camera.PERSPECTIVE_CAMERA;
  11670. this.isIntermediate = false;
  11671. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11672. this.layerMask = 0x0FFFFFFF;
  11673. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11674. // Camera rig members
  11675. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11676. this._rigCameras = new Array();
  11677. // Cache
  11678. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11679. this._projectionMatrix = new BABYLON.Matrix();
  11680. this._postProcesses = new Array();
  11681. this._transformMatrix = BABYLON.Matrix.Zero();
  11682. this._activeMeshes = new BABYLON.SmartArray(256);
  11683. this._globalPosition = BABYLON.Vector3.Zero();
  11684. this._refreshFrustumPlanes = true;
  11685. scene.addCamera(this);
  11686. if (!scene.activeCamera) {
  11687. scene.activeCamera = this;
  11688. }
  11689. this.position = position;
  11690. }
  11691. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11692. get: function () {
  11693. return Camera._PERSPECTIVE_CAMERA;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11699. get: function () {
  11700. return Camera._ORTHOGRAPHIC_CAMERA;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11706. get: function () {
  11707. return Camera._FOVMODE_VERTICAL_FIXED;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11713. get: function () {
  11714. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11720. get: function () {
  11721. return Camera._RIG_MODE_NONE;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11727. get: function () {
  11728. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11734. get: function () {
  11735. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11741. get: function () {
  11742. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11748. get: function () {
  11749. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11755. get: function () {
  11756. return Camera._RIG_MODE_VR;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. /**
  11762. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11763. */
  11764. Camera.prototype.toString = function (fullDetails) {
  11765. var ret = "Name: " + this.name;
  11766. ret += ", type: " + this.getTypeName();
  11767. if (this.animations) {
  11768. for (var i = 0; i < this.animations.length; i++) {
  11769. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11770. }
  11771. }
  11772. if (fullDetails) {
  11773. }
  11774. return ret;
  11775. };
  11776. Object.defineProperty(Camera.prototype, "globalPosition", {
  11777. get: function () {
  11778. return this._globalPosition;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Camera.prototype.getActiveMeshes = function () {
  11784. return this._activeMeshes;
  11785. };
  11786. Camera.prototype.isActiveMesh = function (mesh) {
  11787. return (this._activeMeshes.indexOf(mesh) !== -1);
  11788. };
  11789. //Cache
  11790. Camera.prototype._initCache = function () {
  11791. _super.prototype._initCache.call(this);
  11792. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11793. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11794. this._cache.mode = undefined;
  11795. this._cache.minZ = undefined;
  11796. this._cache.maxZ = undefined;
  11797. this._cache.fov = undefined;
  11798. this._cache.aspectRatio = undefined;
  11799. this._cache.orthoLeft = undefined;
  11800. this._cache.orthoRight = undefined;
  11801. this._cache.orthoBottom = undefined;
  11802. this._cache.orthoTop = undefined;
  11803. this._cache.renderWidth = undefined;
  11804. this._cache.renderHeight = undefined;
  11805. };
  11806. Camera.prototype._updateCache = function (ignoreParentClass) {
  11807. if (!ignoreParentClass) {
  11808. _super.prototype._updateCache.call(this);
  11809. }
  11810. var engine = this.getEngine();
  11811. this._cache.position.copyFrom(this.position);
  11812. this._cache.upVector.copyFrom(this.upVector);
  11813. this._cache.mode = this.mode;
  11814. this._cache.minZ = this.minZ;
  11815. this._cache.maxZ = this.maxZ;
  11816. this._cache.fov = this.fov;
  11817. this._cache.aspectRatio = engine.getAspectRatio(this);
  11818. this._cache.orthoLeft = this.orthoLeft;
  11819. this._cache.orthoRight = this.orthoRight;
  11820. this._cache.orthoBottom = this.orthoBottom;
  11821. this._cache.orthoTop = this.orthoTop;
  11822. this._cache.renderWidth = engine.getRenderWidth();
  11823. this._cache.renderHeight = engine.getRenderHeight();
  11824. };
  11825. Camera.prototype._updateFromScene = function () {
  11826. this.updateCache();
  11827. this._update();
  11828. };
  11829. // Synchronized
  11830. Camera.prototype._isSynchronized = function () {
  11831. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11832. };
  11833. Camera.prototype._isSynchronizedViewMatrix = function () {
  11834. if (!_super.prototype._isSynchronized.call(this))
  11835. return false;
  11836. return this._cache.position.equals(this.position)
  11837. && this._cache.upVector.equals(this.upVector)
  11838. && this.isSynchronizedWithParent();
  11839. };
  11840. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11841. var check = this._cache.mode === this.mode
  11842. && this._cache.minZ === this.minZ
  11843. && this._cache.maxZ === this.maxZ;
  11844. if (!check) {
  11845. return false;
  11846. }
  11847. var engine = this.getEngine();
  11848. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11849. check = this._cache.fov === this.fov
  11850. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11851. }
  11852. else {
  11853. check = this._cache.orthoLeft === this.orthoLeft
  11854. && this._cache.orthoRight === this.orthoRight
  11855. && this._cache.orthoBottom === this.orthoBottom
  11856. && this._cache.orthoTop === this.orthoTop
  11857. && this._cache.renderWidth === engine.getRenderWidth()
  11858. && this._cache.renderHeight === engine.getRenderHeight();
  11859. }
  11860. return check;
  11861. };
  11862. // Controls
  11863. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11864. };
  11865. Camera.prototype.detachControl = function (element) {
  11866. };
  11867. Camera.prototype._update = function () {
  11868. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11869. this._updateRigCameras();
  11870. }
  11871. this._checkInputs();
  11872. };
  11873. Camera.prototype._checkInputs = function () {
  11874. };
  11875. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11876. // invalidate framebuffer
  11877. if (this._postProcesses.length > 0) {
  11878. this._postProcesses[0].markTextureDirty();
  11879. }
  11880. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11881. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11882. var cam = this._rigCameras[i];
  11883. var rigPostProcess = cam._rigPostProcess;
  11884. // for VR rig, there does not have to be a post process
  11885. if (rigPostProcess) {
  11886. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11887. if (isPass) {
  11888. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11889. cam.isIntermediate = this._postProcesses.length === 0;
  11890. }
  11891. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11892. rigPostProcess.markTextureDirty();
  11893. }
  11894. else {
  11895. cam._postProcesses = this._postProcesses.slice(0);
  11896. }
  11897. }
  11898. };
  11899. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11900. if (insertAt === void 0) { insertAt = null; }
  11901. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11902. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11903. return 0;
  11904. }
  11905. if (insertAt == null || insertAt < 0) {
  11906. this._postProcesses.push(postProcess);
  11907. }
  11908. else {
  11909. this._postProcesses.splice(insertAt, 0, postProcess);
  11910. }
  11911. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11912. return this._postProcesses.indexOf(postProcess);
  11913. };
  11914. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11915. if (atIndices === void 0) { atIndices = null; }
  11916. var result = [];
  11917. var i;
  11918. var index;
  11919. if (!atIndices) {
  11920. var idx = this._postProcesses.indexOf(postProcess);
  11921. if (idx !== -1) {
  11922. this._postProcesses.splice(idx, 1);
  11923. }
  11924. }
  11925. else {
  11926. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11927. // iterate descending, so can just splice as we go
  11928. for (i = atIndices.length - 1; i >= 0; i--) {
  11929. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11930. result.push(i);
  11931. continue;
  11932. }
  11933. this._postProcesses.splice(index, 1);
  11934. }
  11935. }
  11936. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11937. return result;
  11938. };
  11939. Camera.prototype.getWorldMatrix = function () {
  11940. if (!this._worldMatrix) {
  11941. this._worldMatrix = BABYLON.Matrix.Identity();
  11942. }
  11943. var viewMatrix = this.getViewMatrix();
  11944. viewMatrix.invertToRef(this._worldMatrix);
  11945. return this._worldMatrix;
  11946. };
  11947. Camera.prototype._getViewMatrix = function () {
  11948. return BABYLON.Matrix.Identity();
  11949. };
  11950. Camera.prototype.getViewMatrix = function (force) {
  11951. this._computedViewMatrix = this._computeViewMatrix(force);
  11952. if (!force && this._isSynchronizedViewMatrix()) {
  11953. return this._computedViewMatrix;
  11954. }
  11955. this._refreshFrustumPlanes = true;
  11956. if (!this.parent || !this.parent.getWorldMatrix) {
  11957. this._globalPosition.copyFrom(this.position);
  11958. }
  11959. else {
  11960. if (!this._worldMatrix) {
  11961. this._worldMatrix = BABYLON.Matrix.Identity();
  11962. }
  11963. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11964. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11965. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11966. this._computedViewMatrix.invert();
  11967. this._markSyncedWithParent();
  11968. }
  11969. this._currentRenderId = this.getScene().getRenderId();
  11970. return this._computedViewMatrix;
  11971. };
  11972. Camera.prototype._computeViewMatrix = function (force) {
  11973. if (!force && this._isSynchronizedViewMatrix()) {
  11974. return this._computedViewMatrix;
  11975. }
  11976. this._computedViewMatrix = this._getViewMatrix();
  11977. this._currentRenderId = this.getScene().getRenderId();
  11978. return this._computedViewMatrix;
  11979. };
  11980. Camera.prototype.getProjectionMatrix = function (force) {
  11981. if (!force && this._isSynchronizedProjectionMatrix()) {
  11982. return this._projectionMatrix;
  11983. }
  11984. this._refreshFrustumPlanes = true;
  11985. var engine = this.getEngine();
  11986. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11987. if (this.minZ <= 0) {
  11988. this.minZ = 0.1;
  11989. }
  11990. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11991. return this._projectionMatrix;
  11992. }
  11993. var halfWidth = engine.getRenderWidth() / 2.0;
  11994. var halfHeight = engine.getRenderHeight() / 2.0;
  11995. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11996. return this._projectionMatrix;
  11997. };
  11998. Camera.prototype.getTranformationMatrix = function () {
  11999. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12000. return this._transformMatrix;
  12001. };
  12002. Camera.prototype.updateFrustumPlanes = function () {
  12003. if (!this._refreshFrustumPlanes) {
  12004. return;
  12005. }
  12006. this.getTranformationMatrix();
  12007. if (!this._frustumPlanes) {
  12008. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12009. }
  12010. else {
  12011. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12012. }
  12013. this._refreshFrustumPlanes = false;
  12014. };
  12015. Camera.prototype.isInFrustum = function (target) {
  12016. this.updateFrustumPlanes();
  12017. return target.isInFrustum(this._frustumPlanes);
  12018. };
  12019. Camera.prototype.isCompletelyInFrustum = function (target) {
  12020. this.updateFrustumPlanes();
  12021. return target.isCompletelyInFrustum(this._frustumPlanes);
  12022. };
  12023. Camera.prototype.dispose = function () {
  12024. // Animations
  12025. this.getScene().stopAnimation(this);
  12026. // Remove from scene
  12027. this.getScene().removeCamera(this);
  12028. while (this._rigCameras.length > 0) {
  12029. this._rigCameras.pop().dispose();
  12030. }
  12031. // Postprocesses
  12032. for (var i = 0; i < this._postProcesses.length; ++i) {
  12033. this._postProcesses[i].dispose(this);
  12034. }
  12035. _super.prototype.dispose.call(this);
  12036. };
  12037. // ---- Camera rigs section ----
  12038. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12039. while (this._rigCameras.length > 0) {
  12040. this._rigCameras.pop().dispose();
  12041. }
  12042. this.cameraRigMode = mode;
  12043. this._cameraRigParams = {};
  12044. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12045. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12046. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12047. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12048. // create the rig cameras, unless none
  12049. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12050. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12051. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12052. }
  12053. switch (this.cameraRigMode) {
  12054. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12055. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12056. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12057. break;
  12058. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12059. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12060. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12061. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12062. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12063. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12064. break;
  12065. case Camera.RIG_MODE_VR:
  12066. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12067. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12068. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12069. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12070. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12071. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12072. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12073. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12074. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12075. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12076. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12077. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12078. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12079. if (metrics.compensateDistortion) {
  12080. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12081. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12082. }
  12083. break;
  12084. }
  12085. this._cascadePostProcessesToRigCams();
  12086. this._update();
  12087. };
  12088. Camera.prototype._getVRProjectionMatrix = function () {
  12089. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12090. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12091. return this._projectionMatrix;
  12092. };
  12093. Camera.prototype.setCameraRigParameter = function (name, value) {
  12094. if (!this._cameraRigParams) {
  12095. this._cameraRigParams = {};
  12096. }
  12097. this._cameraRigParams[name] = value;
  12098. //provisionnally:
  12099. if (name === "interaxialDistance") {
  12100. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12101. }
  12102. };
  12103. /**
  12104. * needs to be overridden by children so sub has required properties to be copied
  12105. */
  12106. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12107. return null;
  12108. };
  12109. /**
  12110. * May need to be overridden by children
  12111. */
  12112. Camera.prototype._updateRigCameras = function () {
  12113. for (var i = 0; i < this._rigCameras.length; i++) {
  12114. this._rigCameras[i].minZ = this.minZ;
  12115. this._rigCameras[i].maxZ = this.maxZ;
  12116. this._rigCameras[i].fov = this.fov;
  12117. }
  12118. // only update viewport when ANAGLYPH
  12119. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12120. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12121. }
  12122. };
  12123. Camera.prototype._setupInputs = function () {
  12124. };
  12125. Camera.prototype.serialize = function () {
  12126. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12127. // Type
  12128. serializationObject.type = this.getTypeName();
  12129. // Parent
  12130. if (this.parent) {
  12131. serializationObject.parentId = this.parent.id;
  12132. }
  12133. if (this.inputs) {
  12134. this.inputs.serialize(serializationObject);
  12135. }
  12136. // Animations
  12137. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12138. serializationObject.ranges = this.serializeAnimationRanges();
  12139. return serializationObject;
  12140. };
  12141. Camera.prototype.getTypeName = function () {
  12142. return "Camera";
  12143. };
  12144. Camera.prototype.clone = function (name) {
  12145. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12146. };
  12147. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12148. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12149. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12150. switch (type) {
  12151. case "ArcRotateCamera":
  12152. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12153. case "DeviceOrientationCamera":
  12154. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12155. case "FollowCamera":
  12156. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12157. case "ArcFollowCamera":
  12158. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12159. case "GamepadCamera":
  12160. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12161. case "TouchCamera":
  12162. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12163. case "VirtualJoysticksCamera":
  12164. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12165. case "WebVRFreeCamera":
  12166. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12167. case "VRDeviceOrientationFreeCamera":
  12168. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12169. case "AnaglyphArcRotateCamera":
  12170. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12171. case "AnaglyphFreeCamera":
  12172. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12173. case "AnaglyphGamepadCamera":
  12174. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12175. case "AnaglyphUniversalCamera":
  12176. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12177. case "StereoscopicArcRotateCamera":
  12178. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12179. case "StereoscopicFreeCamera":
  12180. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12181. case "StereoscopicGamepadCamera":
  12182. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12183. case "StereoscopicUniversalCamera":
  12184. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12185. case "FreeCamera":
  12186. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12187. default:
  12188. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12189. }
  12190. };
  12191. Camera.Parse = function (parsedCamera, scene) {
  12192. var type = parsedCamera.type;
  12193. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12194. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12195. // Parent
  12196. if (parsedCamera.parentId) {
  12197. camera._waitingParentId = parsedCamera.parentId;
  12198. }
  12199. //If camera has an input manager, let it parse inputs settings
  12200. if (camera.inputs) {
  12201. camera.inputs.parse(parsedCamera);
  12202. camera._setupInputs();
  12203. }
  12204. // Target
  12205. if (parsedCamera.target) {
  12206. if (camera.setTarget) {
  12207. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12208. }
  12209. }
  12210. // Apply 3d rig, when found
  12211. if (parsedCamera.cameraRigMode) {
  12212. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12213. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12214. }
  12215. // Animations
  12216. if (parsedCamera.animations) {
  12217. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12218. var parsedAnimation = parsedCamera.animations[animationIndex];
  12219. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12220. }
  12221. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12222. }
  12223. if (parsedCamera.autoAnimate) {
  12224. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12225. }
  12226. return camera;
  12227. };
  12228. // Statics
  12229. Camera._PERSPECTIVE_CAMERA = 0;
  12230. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12231. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12232. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12233. Camera._RIG_MODE_NONE = 0;
  12234. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12235. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12236. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12237. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12238. Camera._RIG_MODE_VR = 20;
  12239. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12240. __decorate([
  12241. BABYLON.serializeAsVector3()
  12242. ], Camera.prototype, "position", void 0);
  12243. __decorate([
  12244. BABYLON.serializeAsVector3()
  12245. ], Camera.prototype, "upVector", void 0);
  12246. __decorate([
  12247. BABYLON.serialize()
  12248. ], Camera.prototype, "orthoLeft", void 0);
  12249. __decorate([
  12250. BABYLON.serialize()
  12251. ], Camera.prototype, "orthoRight", void 0);
  12252. __decorate([
  12253. BABYLON.serialize()
  12254. ], Camera.prototype, "orthoBottom", void 0);
  12255. __decorate([
  12256. BABYLON.serialize()
  12257. ], Camera.prototype, "orthoTop", void 0);
  12258. __decorate([
  12259. BABYLON.serialize()
  12260. ], Camera.prototype, "fov", void 0);
  12261. __decorate([
  12262. BABYLON.serialize()
  12263. ], Camera.prototype, "minZ", void 0);
  12264. __decorate([
  12265. BABYLON.serialize()
  12266. ], Camera.prototype, "maxZ", void 0);
  12267. __decorate([
  12268. BABYLON.serialize()
  12269. ], Camera.prototype, "inertia", void 0);
  12270. __decorate([
  12271. BABYLON.serialize()
  12272. ], Camera.prototype, "mode", void 0);
  12273. __decorate([
  12274. BABYLON.serialize()
  12275. ], Camera.prototype, "layerMask", void 0);
  12276. __decorate([
  12277. BABYLON.serialize()
  12278. ], Camera.prototype, "fovMode", void 0);
  12279. __decorate([
  12280. BABYLON.serialize()
  12281. ], Camera.prototype, "cameraRigMode", void 0);
  12282. __decorate([
  12283. BABYLON.serialize()
  12284. ], Camera.prototype, "interaxialDistance", void 0);
  12285. __decorate([
  12286. BABYLON.serialize()
  12287. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12288. return Camera;
  12289. })(BABYLON.Node);
  12290. BABYLON.Camera = Camera;
  12291. })(BABYLON || (BABYLON = {}));
  12292. var BABYLON;
  12293. (function (BABYLON) {
  12294. BABYLON.CameraInputTypes = {};
  12295. var CameraInputsManager = (function () {
  12296. function CameraInputsManager(camera) {
  12297. this.attached = {};
  12298. this.camera = camera;
  12299. this.checkInputs = function () { };
  12300. }
  12301. CameraInputsManager.prototype.add = function (input) {
  12302. var type = input.getSimpleName();
  12303. if (this.attached[type]) {
  12304. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12305. return;
  12306. }
  12307. this.attached[type] = input;
  12308. input.camera = this.camera;
  12309. //for checkInputs, we are dynamically creating a function
  12310. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12311. if (input.checkInputs) {
  12312. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12313. }
  12314. if (this.attachedElement) {
  12315. input.attachControl(this.attachedElement);
  12316. }
  12317. };
  12318. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12319. for (var cam in this.attached) {
  12320. var input = this.attached[cam];
  12321. if (input === inputToRemove) {
  12322. input.detachControl(this.attachedElement);
  12323. delete this.attached[cam];
  12324. this.rebuildInputCheck();
  12325. }
  12326. }
  12327. };
  12328. CameraInputsManager.prototype.removeByType = function (inputType) {
  12329. for (var cam in this.attached) {
  12330. var input = this.attached[cam];
  12331. if (input.getTypeName() === inputType) {
  12332. input.detachControl(this.attachedElement);
  12333. delete this.attached[cam];
  12334. this.rebuildInputCheck();
  12335. }
  12336. }
  12337. };
  12338. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12339. var current = this.checkInputs;
  12340. return function () {
  12341. current();
  12342. fn();
  12343. };
  12344. };
  12345. CameraInputsManager.prototype.attachInput = function (input) {
  12346. input.attachControl(this.attachedElement, this.noPreventDefault);
  12347. };
  12348. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12349. if (this.attachedElement) {
  12350. return;
  12351. }
  12352. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12353. this.attachedElement = element;
  12354. this.noPreventDefault = noPreventDefault;
  12355. for (var cam in this.attached) {
  12356. var input = this.attached[cam];
  12357. this.attached[cam].attachControl(element, noPreventDefault);
  12358. }
  12359. };
  12360. CameraInputsManager.prototype.detachElement = function (element) {
  12361. if (this.attachedElement !== element) {
  12362. return;
  12363. }
  12364. for (var cam in this.attached) {
  12365. var input = this.attached[cam];
  12366. this.attached[cam].detachControl(element);
  12367. }
  12368. this.attachedElement = null;
  12369. };
  12370. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12371. this.checkInputs = function () { };
  12372. for (var cam in this.attached) {
  12373. var input = this.attached[cam];
  12374. if (input.checkInputs) {
  12375. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12376. }
  12377. }
  12378. };
  12379. CameraInputsManager.prototype.clear = function () {
  12380. if (this.attachedElement) {
  12381. this.detachElement(this.attachedElement);
  12382. }
  12383. this.attached = {};
  12384. this.attachedElement = null;
  12385. this.checkInputs = function () { };
  12386. };
  12387. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12388. var inputs = {};
  12389. for (var cam in this.attached) {
  12390. var input = this.attached[cam];
  12391. var res = BABYLON.SerializationHelper.Serialize(input);
  12392. inputs[input.getTypeName()] = res;
  12393. }
  12394. serializedCamera.inputsmgr = inputs;
  12395. };
  12396. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12397. var parsedInputs = parsedCamera.inputsmgr;
  12398. if (parsedInputs) {
  12399. this.clear();
  12400. for (var n in parsedInputs) {
  12401. var construct = BABYLON.CameraInputTypes[n];
  12402. if (construct) {
  12403. var parsedinput = parsedInputs[n];
  12404. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12405. this.add(input);
  12406. }
  12407. }
  12408. }
  12409. else {
  12410. //2016-03-08 this part is for managing backward compatibility
  12411. for (var n in this.attached) {
  12412. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12413. if (construct) {
  12414. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12415. this.remove(this.attached[n]);
  12416. this.add(input);
  12417. }
  12418. }
  12419. }
  12420. };
  12421. return CameraInputsManager;
  12422. })();
  12423. BABYLON.CameraInputsManager = CameraInputsManager;
  12424. })(BABYLON || (BABYLON = {}));
  12425. var BABYLON;
  12426. (function (BABYLON) {
  12427. var FreeCameraMouseInput = (function () {
  12428. function FreeCameraMouseInput(touchEnabled) {
  12429. if (touchEnabled === void 0) { touchEnabled = true; }
  12430. this.touchEnabled = touchEnabled;
  12431. this.angularSensibility = 2000.0;
  12432. }
  12433. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12434. var _this = this;
  12435. if (!this._pointerInput) {
  12436. var camera = this.camera;
  12437. var engine = this.camera.getEngine();
  12438. this._pointerInput = function (p, s) {
  12439. var evt = p.event;
  12440. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12441. return;
  12442. }
  12443. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12444. try {
  12445. evt.srcElement.setPointerCapture(evt.pointerId);
  12446. }
  12447. catch (e) {
  12448. }
  12449. _this.previousPosition = {
  12450. x: evt.clientX,
  12451. y: evt.clientY
  12452. };
  12453. if (!noPreventDefault) {
  12454. evt.preventDefault();
  12455. element.focus();
  12456. }
  12457. }
  12458. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12459. try {
  12460. evt.srcElement.releasePointerCapture(evt.pointerId);
  12461. }
  12462. catch (e) {
  12463. }
  12464. _this.previousPosition = null;
  12465. if (!noPreventDefault) {
  12466. evt.preventDefault();
  12467. }
  12468. }
  12469. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12470. if (!_this.previousPosition && !engine.isPointerLock) {
  12471. return;
  12472. }
  12473. var offsetX;
  12474. var offsetY;
  12475. if (!engine.isPointerLock) {
  12476. offsetX = evt.clientX - _this.previousPosition.x;
  12477. offsetY = evt.clientY - _this.previousPosition.y;
  12478. }
  12479. else {
  12480. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12481. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12482. }
  12483. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12484. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12485. _this.previousPosition = {
  12486. x: evt.clientX,
  12487. y: evt.clientY
  12488. };
  12489. if (!noPreventDefault) {
  12490. evt.preventDefault();
  12491. }
  12492. }
  12493. };
  12494. }
  12495. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12496. };
  12497. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12498. if (this._observer && element) {
  12499. this.camera.getScene().onPointerObservable.remove(this._observer);
  12500. this._observer = null;
  12501. this.previousPosition = null;
  12502. }
  12503. };
  12504. FreeCameraMouseInput.prototype.getTypeName = function () {
  12505. return "FreeCameraMouseInput";
  12506. };
  12507. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12508. return "mouse";
  12509. };
  12510. __decorate([
  12511. BABYLON.serialize()
  12512. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12513. return FreeCameraMouseInput;
  12514. })();
  12515. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12516. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12517. })(BABYLON || (BABYLON = {}));
  12518. var BABYLON;
  12519. (function (BABYLON) {
  12520. var FreeCameraKeyboardMoveInput = (function () {
  12521. function FreeCameraKeyboardMoveInput() {
  12522. this._keys = [];
  12523. this.keysUp = [38];
  12524. this.keysDown = [40];
  12525. this.keysLeft = [37];
  12526. this.keysRight = [39];
  12527. }
  12528. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12529. var _this = this;
  12530. if (!this._onKeyDown) {
  12531. element.tabIndex = 1;
  12532. this._onKeyDown = function (evt) {
  12533. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12534. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12535. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12536. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12537. var index = _this._keys.indexOf(evt.keyCode);
  12538. if (index === -1) {
  12539. _this._keys.push(evt.keyCode);
  12540. }
  12541. if (!noPreventDefault) {
  12542. evt.preventDefault();
  12543. }
  12544. }
  12545. };
  12546. this._onKeyUp = function (evt) {
  12547. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12548. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12549. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12550. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12551. var index = _this._keys.indexOf(evt.keyCode);
  12552. if (index >= 0) {
  12553. _this._keys.splice(index, 1);
  12554. }
  12555. if (!noPreventDefault) {
  12556. evt.preventDefault();
  12557. }
  12558. }
  12559. };
  12560. element.addEventListener("keydown", this._onKeyDown, false);
  12561. element.addEventListener("keyup", this._onKeyUp, false);
  12562. BABYLON.Tools.RegisterTopRootEvents([
  12563. { name: "blur", handler: this._onLostFocus }
  12564. ]);
  12565. }
  12566. };
  12567. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12568. if (this._onKeyDown) {
  12569. element.removeEventListener("keydown", this._onKeyDown);
  12570. element.removeEventListener("keyup", this._onKeyUp);
  12571. BABYLON.Tools.UnregisterTopRootEvents([
  12572. { name: "blur", handler: this._onLostFocus }
  12573. ]);
  12574. this._keys = [];
  12575. this._onKeyDown = null;
  12576. this._onKeyUp = null;
  12577. }
  12578. };
  12579. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12580. if (this._onKeyDown) {
  12581. var camera = this.camera;
  12582. // Keyboard
  12583. for (var index = 0; index < this._keys.length; index++) {
  12584. var keyCode = this._keys[index];
  12585. var speed = camera._computeLocalCameraSpeed();
  12586. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12587. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12588. }
  12589. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12590. camera._localDirection.copyFromFloats(0, 0, speed);
  12591. }
  12592. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12593. camera._localDirection.copyFromFloats(speed, 0, 0);
  12594. }
  12595. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12596. camera._localDirection.copyFromFloats(0, 0, -speed);
  12597. }
  12598. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12599. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12600. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12601. }
  12602. }
  12603. };
  12604. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12605. return "FreeCameraKeyboardMoveInput";
  12606. };
  12607. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12608. this._keys = [];
  12609. };
  12610. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12611. return "keyboard";
  12612. };
  12613. __decorate([
  12614. BABYLON.serialize()
  12615. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12616. __decorate([
  12617. BABYLON.serialize()
  12618. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12619. __decorate([
  12620. BABYLON.serialize()
  12621. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12622. __decorate([
  12623. BABYLON.serialize()
  12624. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12625. return FreeCameraKeyboardMoveInput;
  12626. })();
  12627. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12628. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12629. })(BABYLON || (BABYLON = {}));
  12630. var BABYLON;
  12631. (function (BABYLON) {
  12632. var FreeCameraTouchInput = (function () {
  12633. function FreeCameraTouchInput() {
  12634. this._offsetX = null;
  12635. this._offsetY = null;
  12636. this._pointerCount = 0;
  12637. this._pointerPressed = [];
  12638. this.touchAngularSensibility = 200000.0;
  12639. this.touchMoveSensibility = 250.0;
  12640. }
  12641. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12642. var _this = this;
  12643. var previousPosition;
  12644. if (this._pointerInput === undefined) {
  12645. this._onLostFocus = function (evt) {
  12646. _this._offsetX = null;
  12647. _this._offsetY = null;
  12648. };
  12649. this._pointerInput = function (p, s) {
  12650. var evt = p.event;
  12651. if (evt.pointerType === "mouse") {
  12652. return;
  12653. }
  12654. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12655. if (!noPreventDefault) {
  12656. evt.preventDefault();
  12657. }
  12658. _this._pointerPressed.push(evt.pointerId);
  12659. if (_this._pointerPressed.length !== 1) {
  12660. return;
  12661. }
  12662. previousPosition = {
  12663. x: evt.clientX,
  12664. y: evt.clientY
  12665. };
  12666. }
  12667. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12668. if (!noPreventDefault) {
  12669. evt.preventDefault();
  12670. }
  12671. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12672. if (index === -1) {
  12673. return;
  12674. }
  12675. _this._pointerPressed.splice(index, 1);
  12676. if (index != 0) {
  12677. return;
  12678. }
  12679. previousPosition = null;
  12680. _this._offsetX = null;
  12681. _this._offsetY = null;
  12682. }
  12683. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12684. if (!noPreventDefault) {
  12685. evt.preventDefault();
  12686. }
  12687. if (!previousPosition) {
  12688. return;
  12689. }
  12690. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12691. if (index != 0) {
  12692. return;
  12693. }
  12694. _this._offsetX = evt.clientX - previousPosition.x;
  12695. _this._offsetY = -(evt.clientY - previousPosition.y);
  12696. }
  12697. };
  12698. }
  12699. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12700. element.addEventListener("blur", this._onLostFocus);
  12701. };
  12702. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12703. if (this._pointerInput && element) {
  12704. this.camera.getScene().onPointerObservable.remove(this._observer);
  12705. this._observer = null;
  12706. element.removeEventListener("blur", this._onLostFocus);
  12707. this._onLostFocus = null;
  12708. this._pointerPressed = [];
  12709. this._offsetX = null;
  12710. this._offsetY = null;
  12711. this._pointerCount = 0;
  12712. }
  12713. };
  12714. FreeCameraTouchInput.prototype.checkInputs = function () {
  12715. if (this._offsetX) {
  12716. var camera = this.camera;
  12717. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12718. if (this._pointerPressed.length > 1) {
  12719. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12720. }
  12721. else {
  12722. var speed = camera._computeLocalCameraSpeed();
  12723. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12724. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12725. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12726. }
  12727. }
  12728. };
  12729. FreeCameraTouchInput.prototype.getTypeName = function () {
  12730. return "FreeCameraTouchInput";
  12731. };
  12732. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12733. return "touch";
  12734. };
  12735. __decorate([
  12736. BABYLON.serialize()
  12737. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12738. __decorate([
  12739. BABYLON.serialize()
  12740. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12741. return FreeCameraTouchInput;
  12742. })();
  12743. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12744. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12745. })(BABYLON || (BABYLON = {}));
  12746. var BABYLON;
  12747. (function (BABYLON) {
  12748. var FreeCameraDeviceOrientationInput = (function () {
  12749. function FreeCameraDeviceOrientationInput() {
  12750. var _this = this;
  12751. this._screenOrientationAngle = 0;
  12752. this._screenQuaternion = new BABYLON.Quaternion();
  12753. this._alpha = 0;
  12754. this._beta = 0;
  12755. this._gamma = 0;
  12756. this._orientationChanged = function () {
  12757. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12758. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12759. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12760. };
  12761. this._deviceOrientation = function (evt) {
  12762. _this._alpha = evt.alpha;
  12763. _this._beta = evt.beta;
  12764. _this._gamma = evt.gamma;
  12765. };
  12766. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12767. this._orientationChanged();
  12768. }
  12769. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12770. get: function () {
  12771. return this._camera;
  12772. },
  12773. set: function (camera) {
  12774. this._camera = camera;
  12775. if (!this._camera.rotationQuaternion)
  12776. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12777. },
  12778. enumerable: true,
  12779. configurable: true
  12780. });
  12781. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12782. window.addEventListener("orientationchange", this._orientationChanged);
  12783. window.addEventListener("deviceorientation", this._deviceOrientation);
  12784. };
  12785. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12786. window.removeEventListener("orientationchange", this._orientationChanged);
  12787. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12788. };
  12789. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12790. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12791. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12792. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12793. //Mirror on XY Plane
  12794. this._camera.rotationQuaternion.z *= -1;
  12795. this._camera.rotationQuaternion.w *= -1;
  12796. };
  12797. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12798. return "FreeCameraDeviceOrientationInput";
  12799. };
  12800. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12801. return "deviceOrientation";
  12802. };
  12803. return FreeCameraDeviceOrientationInput;
  12804. })();
  12805. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12806. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12807. })(BABYLON || (BABYLON = {}));
  12808. var BABYLON;
  12809. (function (BABYLON) {
  12810. var FreeCameraVRDeviceOrientationInput = (function () {
  12811. function FreeCameraVRDeviceOrientationInput() {
  12812. this.alphaCorrection = 1;
  12813. this.betaCorrection = 1;
  12814. this.gammaCorrection = 1;
  12815. this._alpha = 0;
  12816. this._beta = 0;
  12817. this._gamma = 0;
  12818. this._dirty = false;
  12819. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12820. }
  12821. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12822. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12823. };
  12824. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12825. var camera = this.camera;
  12826. this._alpha = evt.alpha;
  12827. this._beta = evt.beta;
  12828. this._gamma = evt.gamma;
  12829. this._dirty = true;
  12830. };
  12831. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12832. if (this._dirty) {
  12833. this._dirty = false;
  12834. var rotationX = this._gamma;
  12835. if (rotationX < 0) {
  12836. rotationX = 90 + rotationX;
  12837. }
  12838. else {
  12839. // Incline it in the correct angle.
  12840. rotationX = 270 - rotationX;
  12841. }
  12842. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12843. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12844. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12845. }
  12846. };
  12847. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12848. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12849. };
  12850. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12851. return "FreeCameraVRDeviceOrientationInput";
  12852. };
  12853. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12854. return "VRDeviceOrientation";
  12855. };
  12856. return FreeCameraVRDeviceOrientationInput;
  12857. })();
  12858. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12859. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12860. })(BABYLON || (BABYLON = {}));
  12861. var BABYLON;
  12862. (function (BABYLON) {
  12863. var FreeCameraGamepadInput = (function () {
  12864. function FreeCameraGamepadInput() {
  12865. this.gamepadAngularSensibility = 200;
  12866. this.gamepadMoveSensibility = 40;
  12867. }
  12868. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12869. var _this = this;
  12870. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12871. };
  12872. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12873. if (this._gamepads) {
  12874. this._gamepads.dispose();
  12875. }
  12876. this.gamepad = null;
  12877. };
  12878. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12879. if (this.gamepad) {
  12880. var camera = this.camera;
  12881. var LSValues = this.gamepad.leftStick;
  12882. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12883. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12884. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12885. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12886. var RSValues = this.gamepad.rightStick;
  12887. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12888. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12889. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12890. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12891. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12892. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12893. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12894. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12895. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12896. }
  12897. };
  12898. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12899. // Only the first gamepad can control the camera
  12900. if (gamepad.index === 0) {
  12901. this.gamepad = gamepad;
  12902. }
  12903. };
  12904. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12905. return "FreeCameraGamepadInput";
  12906. };
  12907. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12908. return "gamepad";
  12909. };
  12910. __decorate([
  12911. BABYLON.serialize()
  12912. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12913. __decorate([
  12914. BABYLON.serialize()
  12915. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12916. return FreeCameraGamepadInput;
  12917. })();
  12918. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12919. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12920. })(BABYLON || (BABYLON = {}));
  12921. var BABYLON;
  12922. (function (BABYLON) {
  12923. var ArcRotateCameraKeyboardMoveInput = (function () {
  12924. function ArcRotateCameraKeyboardMoveInput() {
  12925. this._keys = [];
  12926. this.keysUp = [38];
  12927. this.keysDown = [40];
  12928. this.keysLeft = [37];
  12929. this.keysRight = [39];
  12930. }
  12931. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12932. var _this = this;
  12933. element.tabIndex = 1;
  12934. this._onKeyDown = function (evt) {
  12935. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12936. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12937. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12938. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12939. var index = _this._keys.indexOf(evt.keyCode);
  12940. if (index === -1) {
  12941. _this._keys.push(evt.keyCode);
  12942. }
  12943. if (evt.preventDefault) {
  12944. if (!noPreventDefault) {
  12945. evt.preventDefault();
  12946. }
  12947. }
  12948. }
  12949. };
  12950. this._onKeyUp = function (evt) {
  12951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12954. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12955. var index = _this._keys.indexOf(evt.keyCode);
  12956. if (index >= 0) {
  12957. _this._keys.splice(index, 1);
  12958. }
  12959. if (evt.preventDefault) {
  12960. if (!noPreventDefault) {
  12961. evt.preventDefault();
  12962. }
  12963. }
  12964. }
  12965. };
  12966. this._onLostFocus = function () {
  12967. _this._keys = [];
  12968. };
  12969. element.addEventListener("keydown", this._onKeyDown, false);
  12970. element.addEventListener("keyup", this._onKeyUp, false);
  12971. BABYLON.Tools.RegisterTopRootEvents([
  12972. { name: "blur", handler: this._onLostFocus }
  12973. ]);
  12974. };
  12975. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12976. element.removeEventListener("keydown", this._onKeyDown);
  12977. element.removeEventListener("keyup", this._onKeyUp);
  12978. BABYLON.Tools.UnregisterTopRootEvents([
  12979. { name: "blur", handler: this._onLostFocus }
  12980. ]);
  12981. this._keys = [];
  12982. this._onKeyDown = null;
  12983. this._onKeyUp = null;
  12984. this._onLostFocus = null;
  12985. };
  12986. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12987. if (this._onKeyDown) {
  12988. var camera = this.camera;
  12989. for (var index = 0; index < this._keys.length; index++) {
  12990. var keyCode = this._keys[index];
  12991. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12992. camera.inertialAlphaOffset -= 0.01;
  12993. }
  12994. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12995. camera.inertialBetaOffset -= 0.01;
  12996. }
  12997. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12998. camera.inertialAlphaOffset += 0.01;
  12999. }
  13000. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13001. camera.inertialBetaOffset += 0.01;
  13002. }
  13003. }
  13004. }
  13005. };
  13006. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13007. return "ArcRotateCameraKeyboardMoveInput";
  13008. };
  13009. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13010. return "keyboard";
  13011. };
  13012. __decorate([
  13013. BABYLON.serialize()
  13014. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13015. __decorate([
  13016. BABYLON.serialize()
  13017. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13018. __decorate([
  13019. BABYLON.serialize()
  13020. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13021. __decorate([
  13022. BABYLON.serialize()
  13023. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13024. return ArcRotateCameraKeyboardMoveInput;
  13025. })();
  13026. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13027. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13028. })(BABYLON || (BABYLON = {}));
  13029. var BABYLON;
  13030. (function (BABYLON) {
  13031. var ArcRotateCameraMouseWheelInput = (function () {
  13032. function ArcRotateCameraMouseWheelInput() {
  13033. this.wheelPrecision = 3.0;
  13034. }
  13035. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13036. var _this = this;
  13037. this._wheel = function (p, s) {
  13038. //sanity check - this should be a PointerWheel event.
  13039. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13040. return;
  13041. var event = p.event;
  13042. var delta = 0;
  13043. if (event.wheelDelta) {
  13044. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13045. }
  13046. else if (event.detail) {
  13047. delta = -event.detail / _this.wheelPrecision;
  13048. }
  13049. if (delta)
  13050. _this.camera.inertialRadiusOffset += delta;
  13051. if (event.preventDefault) {
  13052. if (!noPreventDefault) {
  13053. event.preventDefault();
  13054. }
  13055. }
  13056. };
  13057. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13058. };
  13059. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13060. if (this._observer && element) {
  13061. this.camera.getScene().onPointerObservable.remove(this._observer);
  13062. this._observer = null;
  13063. this._wheel = null;
  13064. }
  13065. };
  13066. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13067. return "ArcRotateCameraMouseWheelInput";
  13068. };
  13069. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13070. return "mousewheel";
  13071. };
  13072. __decorate([
  13073. BABYLON.serialize()
  13074. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13075. return ArcRotateCameraMouseWheelInput;
  13076. })();
  13077. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13078. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13079. })(BABYLON || (BABYLON = {}));
  13080. var BABYLON;
  13081. (function (BABYLON) {
  13082. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13083. var ArcRotateCameraPointersInput = (function () {
  13084. function ArcRotateCameraPointersInput() {
  13085. this.angularSensibilityX = 1000.0;
  13086. this.angularSensibilityY = 1000.0;
  13087. this.pinchPrecision = 6.0;
  13088. this.panningSensibility = 50.0;
  13089. this._isRightClick = false;
  13090. this._isCtrlPushed = false;
  13091. this.pinchInwards = true;
  13092. }
  13093. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13094. var _this = this;
  13095. var engine = this.camera.getEngine();
  13096. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13097. var pointA, pointB;
  13098. var previousPinchDistance = 0;
  13099. this._pointerInput = function (p, s) {
  13100. var evt = p.event;
  13101. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13102. try {
  13103. evt.srcElement.setPointerCapture(evt.pointerId);
  13104. }
  13105. catch (e) {
  13106. }
  13107. // Manage panning with right click
  13108. _this._isRightClick = evt.button === 2;
  13109. // manage pointers
  13110. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13111. if (pointA === undefined) {
  13112. pointA = cacheSoloPointer;
  13113. }
  13114. else if (pointB === undefined) {
  13115. pointB = cacheSoloPointer;
  13116. }
  13117. if (!noPreventDefault) {
  13118. evt.preventDefault();
  13119. element.focus();
  13120. }
  13121. }
  13122. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13123. try {
  13124. evt.srcElement.releasePointerCapture(evt.pointerId);
  13125. }
  13126. catch (e) {
  13127. }
  13128. cacheSoloPointer = null;
  13129. previousPinchDistance = 0;
  13130. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13131. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13132. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13133. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13134. pointA = pointB = undefined;
  13135. if (!noPreventDefault) {
  13136. evt.preventDefault();
  13137. }
  13138. }
  13139. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13140. if (!noPreventDefault) {
  13141. evt.preventDefault();
  13142. }
  13143. // One button down
  13144. if (pointA && pointB === undefined) {
  13145. if (_this.panningSensibility !== 0 &&
  13146. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  13147. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  13148. _this.camera
  13149. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13150. _this.camera
  13151. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13152. }
  13153. else {
  13154. var offsetX = evt.clientX - cacheSoloPointer.x;
  13155. var offsetY = evt.clientY - cacheSoloPointer.y;
  13156. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13157. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13158. }
  13159. cacheSoloPointer.x = evt.clientX;
  13160. cacheSoloPointer.y = evt.clientY;
  13161. }
  13162. else if (pointA && pointB) {
  13163. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13164. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13165. ed.x = evt.clientX;
  13166. ed.y = evt.clientY;
  13167. var direction = _this.pinchInwards ? 1 : -1;
  13168. var distX = pointA.x - pointB.x;
  13169. var distY = pointA.y - pointB.y;
  13170. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13171. if (previousPinchDistance === 0) {
  13172. previousPinchDistance = pinchSquaredDistance;
  13173. return;
  13174. }
  13175. if (pinchSquaredDistance !== previousPinchDistance) {
  13176. _this.camera
  13177. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13178. (_this.pinchPrecision *
  13179. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13180. direction);
  13181. previousPinchDistance = pinchSquaredDistance;
  13182. }
  13183. }
  13184. }
  13185. };
  13186. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13187. this._onContextMenu = function (evt) {
  13188. evt.preventDefault();
  13189. };
  13190. if (!this.camera._useCtrlForPanning) {
  13191. element.addEventListener("contextmenu", this._onContextMenu, false);
  13192. }
  13193. this._onLostFocus = function () {
  13194. //this._keys = [];
  13195. pointA = pointB = undefined;
  13196. previousPinchDistance = 0;
  13197. cacheSoloPointer = null;
  13198. };
  13199. this._onKeyDown = function (evt) {
  13200. _this._isCtrlPushed = evt.ctrlKey;
  13201. };
  13202. this._onKeyUp = function (evt) {
  13203. _this._isCtrlPushed = evt.ctrlKey;
  13204. };
  13205. this._onMouseMove = function (evt) {
  13206. if (!engine.isPointerLock) {
  13207. return;
  13208. }
  13209. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13210. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13211. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13212. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13213. if (!noPreventDefault) {
  13214. evt.preventDefault();
  13215. }
  13216. };
  13217. this._onGestureStart = function (e) {
  13218. if (window.MSGesture === undefined) {
  13219. return;
  13220. }
  13221. if (!_this._MSGestureHandler) {
  13222. _this._MSGestureHandler = new MSGesture();
  13223. _this._MSGestureHandler.target = element;
  13224. }
  13225. _this._MSGestureHandler.addPointer(e.pointerId);
  13226. };
  13227. this._onGesture = function (e) {
  13228. _this.camera.radius *= e.scale;
  13229. if (e.preventDefault) {
  13230. if (!noPreventDefault) {
  13231. e.stopPropagation();
  13232. e.preventDefault();
  13233. }
  13234. }
  13235. };
  13236. element.addEventListener("mousemove", this._onMouseMove, false);
  13237. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13238. element.addEventListener("MSGestureChange", this._onGesture, false);
  13239. element.addEventListener("keydown", this._onKeyDown, false);
  13240. element.addEventListener("keyup", this._onKeyUp, false);
  13241. BABYLON.Tools.RegisterTopRootEvents([
  13242. { name: "blur", handler: this._onLostFocus }
  13243. ]);
  13244. };
  13245. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13246. if (element && this._observer) {
  13247. this.camera.getScene().onPointerObservable.remove(this._observer);
  13248. this._observer = null;
  13249. element.removeEventListener("contextmenu", this._onContextMenu);
  13250. element.removeEventListener("mousemove", this._onMouseMove);
  13251. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13252. element.removeEventListener("MSGestureChange", this._onGesture);
  13253. element.removeEventListener("keydown", this._onKeyDown);
  13254. element.removeEventListener("keyup", this._onKeyUp);
  13255. this._isRightClick = false;
  13256. this._isCtrlPushed = false;
  13257. this.pinchInwards = true;
  13258. this._onKeyDown = null;
  13259. this._onKeyUp = null;
  13260. this._onMouseMove = null;
  13261. this._onGestureStart = null;
  13262. this._onGesture = null;
  13263. this._MSGestureHandler = null;
  13264. this._onLostFocus = null;
  13265. this._onContextMenu = null;
  13266. }
  13267. BABYLON.Tools.UnregisterTopRootEvents([
  13268. { name: "blur", handler: this._onLostFocus }
  13269. ]);
  13270. };
  13271. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13272. return "ArcRotateCameraPointersInput";
  13273. };
  13274. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13275. return "pointers";
  13276. };
  13277. __decorate([
  13278. BABYLON.serialize()
  13279. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13280. __decorate([
  13281. BABYLON.serialize()
  13282. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13283. __decorate([
  13284. BABYLON.serialize()
  13285. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13286. __decorate([
  13287. BABYLON.serialize()
  13288. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13289. return ArcRotateCameraPointersInput;
  13290. })();
  13291. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13292. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13293. })(BABYLON || (BABYLON = {}));
  13294. var BABYLON;
  13295. (function (BABYLON) {
  13296. var ArcRotateCameraGamepadInput = (function () {
  13297. function ArcRotateCameraGamepadInput() {
  13298. this.gamepadRotationSensibility = 80;
  13299. this.gamepadMoveSensibility = 40;
  13300. }
  13301. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13302. var _this = this;
  13303. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13304. };
  13305. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13306. if (this._gamepads) {
  13307. this._gamepads.dispose();
  13308. }
  13309. this.gamepad = null;
  13310. };
  13311. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13312. if (this.gamepad) {
  13313. var camera = this.camera;
  13314. var RSValues = this.gamepad.rightStick;
  13315. if (RSValues.x != 0) {
  13316. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13317. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13318. camera.inertialAlphaOffset += normalizedRX;
  13319. }
  13320. }
  13321. if (RSValues.y != 0) {
  13322. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13323. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13324. camera.inertialBetaOffset += normalizedRY;
  13325. }
  13326. }
  13327. var LSValues = this.gamepad.leftStick;
  13328. if (LSValues.y != 0) {
  13329. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13330. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13331. this.camera.inertialRadiusOffset -= normalizedLY;
  13332. }
  13333. }
  13334. }
  13335. };
  13336. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13337. // Only the first gamepad can control the camera
  13338. if (gamepad.index === 0) {
  13339. this.gamepad = gamepad;
  13340. }
  13341. };
  13342. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13343. return "ArcRotateCameraGamepadInput";
  13344. };
  13345. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13346. return "gamepad";
  13347. };
  13348. __decorate([
  13349. BABYLON.serialize()
  13350. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13351. __decorate([
  13352. BABYLON.serialize()
  13353. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13354. return ArcRotateCameraGamepadInput;
  13355. })();
  13356. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13357. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13358. })(BABYLON || (BABYLON = {}));
  13359. var BABYLON;
  13360. (function (BABYLON) {
  13361. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13362. function ArcRotateCameraVRDeviceOrientationInput() {
  13363. this.alphaCorrection = 1;
  13364. this.betaCorrection = 1;
  13365. this.gammaCorrection = 1;
  13366. this._alpha = 0;
  13367. this._beta = 0;
  13368. this._gamma = 0;
  13369. this._dirty = false;
  13370. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13371. }
  13372. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13373. this.camera.attachControl(element, noPreventDefault);
  13374. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13375. };
  13376. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13377. var camera = this.camera;
  13378. this._alpha = +evt.alpha | 0;
  13379. this._beta = +evt.beta | 0;
  13380. this._gamma = +evt.gamma | 0;
  13381. this._dirty = true;
  13382. };
  13383. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13384. if (this._dirty) {
  13385. this._dirty = false;
  13386. if (this._gamma < 0) {
  13387. this._gamma = 180 + this._gamma;
  13388. }
  13389. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13390. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13391. }
  13392. };
  13393. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13394. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13395. };
  13396. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13397. return "ArcRotateCameraVRDeviceOrientationInput";
  13398. };
  13399. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13400. return "VRDeviceOrientation";
  13401. };
  13402. return ArcRotateCameraVRDeviceOrientationInput;
  13403. })();
  13404. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13405. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13406. })(BABYLON || (BABYLON = {}));
  13407. var BABYLON;
  13408. (function (BABYLON) {
  13409. var TargetCamera = (function (_super) {
  13410. __extends(TargetCamera, _super);
  13411. function TargetCamera(name, position, scene) {
  13412. _super.call(this, name, position, scene);
  13413. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13414. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13415. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13416. this.speed = 2.0;
  13417. this.noRotationConstraint = false;
  13418. this.lockedTarget = null;
  13419. this._currentTarget = BABYLON.Vector3.Zero();
  13420. this._viewMatrix = BABYLON.Matrix.Zero();
  13421. this._camMatrix = BABYLON.Matrix.Zero();
  13422. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13423. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13424. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13425. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13426. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13427. this._lookAtTemp = BABYLON.Matrix.Zero();
  13428. this._tempMatrix = BABYLON.Matrix.Zero();
  13429. }
  13430. TargetCamera.prototype.getFrontPosition = function (distance) {
  13431. var direction = this.getTarget().subtract(this.position);
  13432. direction.normalize();
  13433. direction.scaleInPlace(distance);
  13434. return this.globalPosition.add(direction);
  13435. };
  13436. TargetCamera.prototype._getLockedTargetPosition = function () {
  13437. if (!this.lockedTarget) {
  13438. return null;
  13439. }
  13440. return this.lockedTarget.position || this.lockedTarget;
  13441. };
  13442. // Cache
  13443. TargetCamera.prototype._initCache = function () {
  13444. _super.prototype._initCache.call(this);
  13445. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13446. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13447. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13448. };
  13449. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13450. if (!ignoreParentClass) {
  13451. _super.prototype._updateCache.call(this);
  13452. }
  13453. var lockedTargetPosition = this._getLockedTargetPosition();
  13454. if (!lockedTargetPosition) {
  13455. this._cache.lockedTarget = null;
  13456. }
  13457. else {
  13458. if (!this._cache.lockedTarget) {
  13459. this._cache.lockedTarget = lockedTargetPosition.clone();
  13460. }
  13461. else {
  13462. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13463. }
  13464. }
  13465. this._cache.rotation.copyFrom(this.rotation);
  13466. if (this.rotationQuaternion)
  13467. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13468. };
  13469. // Synchronized
  13470. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13471. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13472. return false;
  13473. }
  13474. var lockedTargetPosition = this._getLockedTargetPosition();
  13475. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13476. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13477. };
  13478. // Methods
  13479. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13480. var engine = this.getEngine();
  13481. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  13482. };
  13483. // Target
  13484. TargetCamera.prototype.setTarget = function (target) {
  13485. this.upVector.normalize();
  13486. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13487. this._camMatrix.invert();
  13488. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13489. var vDir = target.subtract(this.position);
  13490. if (vDir.x >= 0.0) {
  13491. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13492. }
  13493. else {
  13494. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13495. }
  13496. this.rotation.z = 0;
  13497. if (isNaN(this.rotation.x)) {
  13498. this.rotation.x = 0;
  13499. }
  13500. if (isNaN(this.rotation.y)) {
  13501. this.rotation.y = 0;
  13502. }
  13503. if (isNaN(this.rotation.z)) {
  13504. this.rotation.z = 0;
  13505. }
  13506. if (this.rotationQuaternion) {
  13507. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13508. }
  13509. };
  13510. TargetCamera.prototype.getTarget = function () {
  13511. return this._currentTarget;
  13512. };
  13513. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13514. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13515. };
  13516. TargetCamera.prototype._updatePosition = function () {
  13517. this.position.addInPlace(this.cameraDirection);
  13518. };
  13519. TargetCamera.prototype._checkInputs = function () {
  13520. var needToMove = this._decideIfNeedsToMove();
  13521. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13522. // Move
  13523. if (needToMove) {
  13524. this._updatePosition();
  13525. }
  13526. // Rotate
  13527. if (needToRotate) {
  13528. this.rotation.x += this.cameraRotation.x;
  13529. this.rotation.y += this.cameraRotation.y;
  13530. if (!this.noRotationConstraint) {
  13531. var limit = (Math.PI / 2) * 0.95;
  13532. if (this.rotation.x > limit)
  13533. this.rotation.x = limit;
  13534. if (this.rotation.x < -limit)
  13535. this.rotation.x = -limit;
  13536. }
  13537. }
  13538. // Inertia
  13539. if (needToMove) {
  13540. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13541. this.cameraDirection.x = 0;
  13542. }
  13543. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13544. this.cameraDirection.y = 0;
  13545. }
  13546. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13547. this.cameraDirection.z = 0;
  13548. }
  13549. this.cameraDirection.scaleInPlace(this.inertia);
  13550. }
  13551. if (needToRotate) {
  13552. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13553. this.cameraRotation.x = 0;
  13554. }
  13555. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13556. this.cameraRotation.y = 0;
  13557. }
  13558. this.cameraRotation.scaleInPlace(this.inertia);
  13559. }
  13560. _super.prototype._checkInputs.call(this);
  13561. };
  13562. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13563. if (this.rotationQuaternion) {
  13564. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13565. //update the up vector!
  13566. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13567. }
  13568. else {
  13569. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13570. }
  13571. };
  13572. TargetCamera.prototype._getViewMatrix = function () {
  13573. if (!this.lockedTarget) {
  13574. // Compute
  13575. this._updateCameraRotationMatrix();
  13576. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13577. // Computing target and final matrix
  13578. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13579. }
  13580. else {
  13581. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13582. }
  13583. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13584. return this._viewMatrix;
  13585. };
  13586. /**
  13587. * @override
  13588. * Override Camera.createRigCamera
  13589. */
  13590. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13591. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13592. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13593. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13594. if (!this.rotationQuaternion) {
  13595. this.rotationQuaternion = new BABYLON.Quaternion();
  13596. }
  13597. rigCamera._cameraRigParams = {};
  13598. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13599. }
  13600. return rigCamera;
  13601. }
  13602. return null;
  13603. };
  13604. /**
  13605. * @override
  13606. * Override Camera._updateRigCameras
  13607. */
  13608. TargetCamera.prototype._updateRigCameras = function () {
  13609. var camLeft = this._rigCameras[0];
  13610. var camRight = this._rigCameras[1];
  13611. switch (this.cameraRigMode) {
  13612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13616. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13617. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13618. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13619. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13620. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13621. camLeft.setTarget(this.getTarget());
  13622. camRight.setTarget(this.getTarget());
  13623. break;
  13624. case BABYLON.Camera.RIG_MODE_VR:
  13625. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13626. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13627. camLeft.position.copyFrom(this.position);
  13628. camRight.position.copyFrom(this.position);
  13629. break;
  13630. }
  13631. _super.prototype._updateRigCameras.call(this);
  13632. };
  13633. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13634. if (!this._rigCamTransformMatrix) {
  13635. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13636. }
  13637. var target = this.getTarget();
  13638. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13639. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13640. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13641. };
  13642. TargetCamera.prototype.getTypeName = function () {
  13643. return "TargetCamera";
  13644. };
  13645. __decorate([
  13646. BABYLON.serializeAsVector3()
  13647. ], TargetCamera.prototype, "rotation", void 0);
  13648. __decorate([
  13649. BABYLON.serialize()
  13650. ], TargetCamera.prototype, "speed", void 0);
  13651. __decorate([
  13652. BABYLON.serializeAsMeshReference("lockedTargetId")
  13653. ], TargetCamera.prototype, "lockedTarget", void 0);
  13654. return TargetCamera;
  13655. })(BABYLON.Camera);
  13656. BABYLON.TargetCamera = TargetCamera;
  13657. })(BABYLON || (BABYLON = {}));
  13658. var BABYLON;
  13659. (function (BABYLON) {
  13660. var FreeCamera = (function (_super) {
  13661. __extends(FreeCamera, _super);
  13662. function FreeCamera(name, position, scene) {
  13663. var _this = this;
  13664. _super.call(this, name, position, scene);
  13665. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13666. this.checkCollisions = false;
  13667. this.applyGravity = false;
  13668. this._collider = new BABYLON.Collider();
  13669. this._needMoveForGravity = false;
  13670. this._oldPosition = BABYLON.Vector3.Zero();
  13671. this._diffPosition = BABYLON.Vector3.Zero();
  13672. this._newPosition = BABYLON.Vector3.Zero();
  13673. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13674. if (collidedMesh === void 0) { collidedMesh = null; }
  13675. //TODO move this to the collision coordinator!
  13676. if (_this.getScene().workerCollisions)
  13677. newPosition.multiplyInPlace(_this._collider.radius);
  13678. var updatePosition = function (newPos) {
  13679. _this._newPosition.copyFrom(newPos);
  13680. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13681. var oldPosition = _this.position.clone();
  13682. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13683. _this.position.addInPlace(_this._diffPosition);
  13684. if (_this.onCollide && collidedMesh) {
  13685. _this.onCollide(collidedMesh);
  13686. }
  13687. }
  13688. };
  13689. updatePosition(newPosition);
  13690. };
  13691. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13692. this.inputs.addKeyboard().addMouse();
  13693. }
  13694. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13695. //-- begin properties for backward compatibility for inputs
  13696. get: function () {
  13697. var mouse = this.inputs.attached["mouse"];
  13698. if (mouse)
  13699. return mouse.angularSensibility;
  13700. },
  13701. set: function (value) {
  13702. var mouse = this.inputs.attached["mouse"];
  13703. if (mouse)
  13704. mouse.angularSensibility = value;
  13705. },
  13706. enumerable: true,
  13707. configurable: true
  13708. });
  13709. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13710. get: function () {
  13711. var keyboard = this.inputs.attached["keyboard"];
  13712. if (keyboard)
  13713. return keyboard.keysUp;
  13714. },
  13715. set: function (value) {
  13716. var keyboard = this.inputs.attached["keyboard"];
  13717. if (keyboard)
  13718. keyboard.keysUp = value;
  13719. },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13724. get: function () {
  13725. var keyboard = this.inputs.attached["keyboard"];
  13726. if (keyboard)
  13727. return keyboard.keysDown;
  13728. },
  13729. set: function (value) {
  13730. var keyboard = this.inputs.attached["keyboard"];
  13731. if (keyboard)
  13732. keyboard.keysDown = value;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13738. get: function () {
  13739. var keyboard = this.inputs.attached["keyboard"];
  13740. if (keyboard)
  13741. return keyboard.keysLeft;
  13742. },
  13743. set: function (value) {
  13744. var keyboard = this.inputs.attached["keyboard"];
  13745. if (keyboard)
  13746. keyboard.keysLeft = value;
  13747. },
  13748. enumerable: true,
  13749. configurable: true
  13750. });
  13751. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13752. get: function () {
  13753. var keyboard = this.inputs.attached["keyboard"];
  13754. if (keyboard)
  13755. return keyboard.keysRight;
  13756. },
  13757. set: function (value) {
  13758. var keyboard = this.inputs.attached["keyboard"];
  13759. if (keyboard)
  13760. keyboard.keysRight = value;
  13761. },
  13762. enumerable: true,
  13763. configurable: true
  13764. });
  13765. // Controls
  13766. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13767. this.inputs.attachElement(element, noPreventDefault);
  13768. };
  13769. FreeCamera.prototype.detachControl = function (element) {
  13770. this.inputs.detachElement(element);
  13771. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13772. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13773. };
  13774. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13775. var globalPosition;
  13776. if (this.parent) {
  13777. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13778. }
  13779. else {
  13780. globalPosition = this.position;
  13781. }
  13782. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13783. this._collider.radius = this.ellipsoid;
  13784. //no need for clone, as long as gravity is not on.
  13785. var actualVelocity = velocity;
  13786. //add gravity to the velocity to prevent the dual-collision checking
  13787. if (this.applyGravity) {
  13788. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13789. actualVelocity = velocity.add(this.getScene().gravity);
  13790. }
  13791. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13792. };
  13793. FreeCamera.prototype._checkInputs = function () {
  13794. if (!this._localDirection) {
  13795. this._localDirection = BABYLON.Vector3.Zero();
  13796. this._transformedDirection = BABYLON.Vector3.Zero();
  13797. }
  13798. this.inputs.checkInputs();
  13799. _super.prototype._checkInputs.call(this);
  13800. };
  13801. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13802. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13803. };
  13804. FreeCamera.prototype._updatePosition = function () {
  13805. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13806. this._collideWithWorld(this.cameraDirection);
  13807. }
  13808. else {
  13809. this.position.addInPlace(this.cameraDirection);
  13810. }
  13811. };
  13812. FreeCamera.prototype.dispose = function () {
  13813. this.inputs.clear();
  13814. _super.prototype.dispose.call(this);
  13815. };
  13816. FreeCamera.prototype.getTypeName = function () {
  13817. return "FreeCamera";
  13818. };
  13819. __decorate([
  13820. BABYLON.serializeAsVector3()
  13821. ], FreeCamera.prototype, "ellipsoid", void 0);
  13822. __decorate([
  13823. BABYLON.serialize()
  13824. ], FreeCamera.prototype, "checkCollisions", void 0);
  13825. __decorate([
  13826. BABYLON.serialize()
  13827. ], FreeCamera.prototype, "applyGravity", void 0);
  13828. return FreeCamera;
  13829. })(BABYLON.TargetCamera);
  13830. BABYLON.FreeCamera = FreeCamera;
  13831. })(BABYLON || (BABYLON = {}));
  13832. var BABYLON;
  13833. (function (BABYLON) {
  13834. var FreeCameraInputsManager = (function (_super) {
  13835. __extends(FreeCameraInputsManager, _super);
  13836. function FreeCameraInputsManager(camera) {
  13837. _super.call(this, camera);
  13838. }
  13839. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13840. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13841. return this;
  13842. };
  13843. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13844. if (touchEnabled === void 0) { touchEnabled = true; }
  13845. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13846. return this;
  13847. };
  13848. FreeCameraInputsManager.prototype.addGamepad = function () {
  13849. this.add(new BABYLON.FreeCameraGamepadInput());
  13850. return this;
  13851. };
  13852. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13853. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13854. return this;
  13855. };
  13856. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13857. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13858. return this;
  13859. };
  13860. FreeCameraInputsManager.prototype.addTouch = function () {
  13861. this.add(new BABYLON.FreeCameraTouchInput());
  13862. return this;
  13863. };
  13864. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13865. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13866. return this;
  13867. };
  13868. return FreeCameraInputsManager;
  13869. })(BABYLON.CameraInputsManager);
  13870. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13871. })(BABYLON || (BABYLON = {}));
  13872. var BABYLON;
  13873. (function (BABYLON) {
  13874. var FollowCamera = (function (_super) {
  13875. __extends(FollowCamera, _super);
  13876. function FollowCamera(name, position, scene, target) {
  13877. _super.call(this, name, position, scene);
  13878. this.radius = 12;
  13879. this.rotationOffset = 0;
  13880. this.heightOffset = 4;
  13881. this.cameraAcceleration = 0.05;
  13882. this.maxCameraSpeed = 20;
  13883. this.target = target;
  13884. }
  13885. FollowCamera.prototype.getRadians = function (degrees) {
  13886. return degrees * Math.PI / 180;
  13887. };
  13888. FollowCamera.prototype.follow = function (cameraTarget) {
  13889. if (!cameraTarget)
  13890. return;
  13891. var yRotation;
  13892. if (cameraTarget.rotationQuaternion) {
  13893. var rotMatrix = new BABYLON.Matrix();
  13894. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13895. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13896. }
  13897. else {
  13898. yRotation = cameraTarget.rotation.y;
  13899. }
  13900. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13901. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13902. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13903. var dx = targetX - this.position.x;
  13904. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13905. var dz = (targetZ) - this.position.z;
  13906. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13907. var vy = dy * this.cameraAcceleration;
  13908. var vz = dz * this.cameraAcceleration * 2;
  13909. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13910. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13911. }
  13912. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13913. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13914. }
  13915. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13916. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13917. }
  13918. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13919. this.setTarget(cameraTarget.position);
  13920. };
  13921. FollowCamera.prototype._checkInputs = function () {
  13922. _super.prototype._checkInputs.call(this);
  13923. this.follow(this.target);
  13924. };
  13925. FollowCamera.prototype.getTypeName = function () {
  13926. return "FollowCamera";
  13927. };
  13928. __decorate([
  13929. BABYLON.serialize()
  13930. ], FollowCamera.prototype, "radius", void 0);
  13931. __decorate([
  13932. BABYLON.serialize()
  13933. ], FollowCamera.prototype, "rotationOffset", void 0);
  13934. __decorate([
  13935. BABYLON.serialize()
  13936. ], FollowCamera.prototype, "heightOffset", void 0);
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13943. __decorate([
  13944. BABYLON.serializeAsMeshReference("lockedTargetId")
  13945. ], FollowCamera.prototype, "target", void 0);
  13946. return FollowCamera;
  13947. })(BABYLON.TargetCamera);
  13948. BABYLON.FollowCamera = FollowCamera;
  13949. var ArcFollowCamera = (function (_super) {
  13950. __extends(ArcFollowCamera, _super);
  13951. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13952. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13953. this.alpha = alpha;
  13954. this.beta = beta;
  13955. this.radius = radius;
  13956. this.target = target;
  13957. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13958. this.follow();
  13959. }
  13960. ArcFollowCamera.prototype.follow = function () {
  13961. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13962. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13963. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13964. this.position = this.target.position.add(this._cartesianCoordinates);
  13965. this.setTarget(this.target.position);
  13966. };
  13967. ArcFollowCamera.prototype._checkInputs = function () {
  13968. _super.prototype._checkInputs.call(this);
  13969. this.follow();
  13970. };
  13971. ArcFollowCamera.prototype.getTypeName = function () {
  13972. return "ArcFollowCamera";
  13973. };
  13974. return ArcFollowCamera;
  13975. })(BABYLON.TargetCamera);
  13976. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13977. })(BABYLON || (BABYLON = {}));
  13978. var BABYLON;
  13979. (function (BABYLON) {
  13980. // We're mainly based on the logic defined into the FreeCamera code
  13981. var TouchCamera = (function (_super) {
  13982. __extends(TouchCamera, _super);
  13983. //-- end properties for backward compatibility for inputs
  13984. function TouchCamera(name, position, scene) {
  13985. _super.call(this, name, position, scene);
  13986. this.inputs.addTouch();
  13987. this._setupInputs();
  13988. }
  13989. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13990. //-- Begin properties for backward compatibility for inputs
  13991. get: function () {
  13992. var touch = this.inputs.attached["touch"];
  13993. if (touch)
  13994. return touch.touchAngularSensibility;
  13995. },
  13996. set: function (value) {
  13997. var touch = this.inputs.attached["touch"];
  13998. if (touch)
  13999. touch.touchAngularSensibility = value;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14005. get: function () {
  14006. var touch = this.inputs.attached["touch"];
  14007. if (touch)
  14008. return touch.touchMoveSensibility;
  14009. },
  14010. set: function (value) {
  14011. var touch = this.inputs.attached["touch"];
  14012. if (touch)
  14013. touch.touchMoveSensibility = value;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. TouchCamera.prototype.getTypeName = function () {
  14019. return "TouchCamera";
  14020. };
  14021. TouchCamera.prototype._setupInputs = function () {
  14022. var mouse = this.inputs.attached["mouse"];
  14023. if (mouse) {
  14024. mouse.touchEnabled = false;
  14025. }
  14026. };
  14027. return TouchCamera;
  14028. })(BABYLON.FreeCamera);
  14029. BABYLON.TouchCamera = TouchCamera;
  14030. })(BABYLON || (BABYLON = {}));
  14031. var BABYLON;
  14032. (function (BABYLON) {
  14033. var ArcRotateCamera = (function (_super) {
  14034. __extends(ArcRotateCamera, _super);
  14035. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14036. var _this = this;
  14037. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14038. this.inertialAlphaOffset = 0;
  14039. this.inertialBetaOffset = 0;
  14040. this.inertialRadiusOffset = 0;
  14041. this.lowerAlphaLimit = null;
  14042. this.upperAlphaLimit = null;
  14043. this.lowerBetaLimit = 0.01;
  14044. this.upperBetaLimit = Math.PI;
  14045. this.lowerRadiusLimit = null;
  14046. this.upperRadiusLimit = null;
  14047. this.inertialPanningX = 0;
  14048. this.inertialPanningY = 0;
  14049. //-- end properties for backward compatibility for inputs
  14050. this.zoomOnFactor = 1;
  14051. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14052. this.allowUpsideDown = true;
  14053. this._viewMatrix = new BABYLON.Matrix();
  14054. // Panning
  14055. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14056. this.checkCollisions = false;
  14057. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14058. this._collider = new BABYLON.Collider();
  14059. this._previousPosition = BABYLON.Vector3.Zero();
  14060. this._collisionVelocity = BABYLON.Vector3.Zero();
  14061. this._newPosition = BABYLON.Vector3.Zero();
  14062. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14063. if (collidedMesh === void 0) { collidedMesh = null; }
  14064. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14065. newPosition.multiplyInPlace(_this._collider.radius);
  14066. }
  14067. if (!collidedMesh) {
  14068. _this._previousPosition.copyFrom(_this.position);
  14069. }
  14070. else {
  14071. _this.setPosition(newPosition);
  14072. if (_this.onCollide) {
  14073. _this.onCollide(collidedMesh);
  14074. }
  14075. }
  14076. // Recompute because of constraints
  14077. var cosa = Math.cos(_this.alpha);
  14078. var sina = Math.sin(_this.alpha);
  14079. var cosb = Math.cos(_this.beta);
  14080. var sinb = Math.sin(_this.beta);
  14081. if (sinb === 0) {
  14082. sinb = 0.0001;
  14083. }
  14084. var target = _this._getTargetPosition();
  14085. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14086. _this.position.copyFrom(_this._newPosition);
  14087. var up = _this.upVector;
  14088. if (_this.allowUpsideDown && _this.beta < 0) {
  14089. up = up.clone();
  14090. up = up.negate();
  14091. }
  14092. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14093. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14094. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14095. _this._collisionTriggered = false;
  14096. };
  14097. if (!target) {
  14098. this.target = BABYLON.Vector3.Zero();
  14099. }
  14100. else {
  14101. this.target = target;
  14102. }
  14103. this.alpha = alpha;
  14104. this.beta = beta;
  14105. this.radius = radius;
  14106. this.getViewMatrix();
  14107. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14108. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14109. }
  14110. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14111. //-- begin properties for backward compatibility for inputs
  14112. get: function () {
  14113. var pointers = this.inputs.attached["pointers"];
  14114. if (pointers)
  14115. return pointers.angularSensibilityX;
  14116. },
  14117. set: function (value) {
  14118. var pointers = this.inputs.attached["pointers"];
  14119. if (pointers) {
  14120. pointers.angularSensibilityX = value;
  14121. }
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14127. get: function () {
  14128. var pointers = this.inputs.attached["pointers"];
  14129. if (pointers)
  14130. return pointers.angularSensibilityY;
  14131. },
  14132. set: function (value) {
  14133. var pointers = this.inputs.attached["pointers"];
  14134. if (pointers) {
  14135. pointers.angularSensibilityY = value;
  14136. }
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14142. get: function () {
  14143. var pointers = this.inputs.attached["pointers"];
  14144. if (pointers)
  14145. return pointers.pinchPrecision;
  14146. },
  14147. set: function (value) {
  14148. var pointers = this.inputs.attached["pointers"];
  14149. if (pointers) {
  14150. pointers.pinchPrecision = value;
  14151. }
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14157. get: function () {
  14158. var pointers = this.inputs.attached["pointers"];
  14159. if (pointers)
  14160. return pointers.panningSensibility;
  14161. },
  14162. set: function (value) {
  14163. var pointers = this.inputs.attached["pointers"];
  14164. if (pointers) {
  14165. pointers.panningSensibility = value;
  14166. }
  14167. },
  14168. enumerable: true,
  14169. configurable: true
  14170. });
  14171. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14172. get: function () {
  14173. var keyboard = this.inputs.attached["keyboard"];
  14174. if (keyboard)
  14175. return keyboard.keysUp;
  14176. },
  14177. set: function (value) {
  14178. var keyboard = this.inputs.attached["keyboard"];
  14179. if (keyboard)
  14180. keyboard.keysUp = value;
  14181. },
  14182. enumerable: true,
  14183. configurable: true
  14184. });
  14185. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14186. get: function () {
  14187. var keyboard = this.inputs.attached["keyboard"];
  14188. if (keyboard)
  14189. return keyboard.keysDown;
  14190. },
  14191. set: function (value) {
  14192. var keyboard = this.inputs.attached["keyboard"];
  14193. if (keyboard)
  14194. keyboard.keysDown = value;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14200. get: function () {
  14201. var keyboard = this.inputs.attached["keyboard"];
  14202. if (keyboard)
  14203. return keyboard.keysLeft;
  14204. },
  14205. set: function (value) {
  14206. var keyboard = this.inputs.attached["keyboard"];
  14207. if (keyboard)
  14208. keyboard.keysLeft = value;
  14209. },
  14210. enumerable: true,
  14211. configurable: true
  14212. });
  14213. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14214. get: function () {
  14215. var keyboard = this.inputs.attached["keyboard"];
  14216. if (keyboard)
  14217. return keyboard.keysRight;
  14218. },
  14219. set: function (value) {
  14220. var keyboard = this.inputs.attached["keyboard"];
  14221. if (keyboard)
  14222. keyboard.keysRight = value;
  14223. },
  14224. enumerable: true,
  14225. configurable: true
  14226. });
  14227. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14228. get: function () {
  14229. var mousewheel = this.inputs.attached["mousewheel"];
  14230. if (mousewheel)
  14231. return mousewheel.wheelPrecision;
  14232. },
  14233. set: function (value) {
  14234. var mousewheel = this.inputs.attached["mousewheel"];
  14235. if (mousewheel)
  14236. mousewheel.wheelPrecision = value;
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. // Cache
  14242. ArcRotateCamera.prototype._initCache = function () {
  14243. _super.prototype._initCache.call(this);
  14244. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14245. this._cache.alpha = undefined;
  14246. this._cache.beta = undefined;
  14247. this._cache.radius = undefined;
  14248. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14249. };
  14250. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14251. if (!ignoreParentClass) {
  14252. _super.prototype._updateCache.call(this);
  14253. }
  14254. this._cache.target.copyFrom(this._getTargetPosition());
  14255. this._cache.alpha = this.alpha;
  14256. this._cache.beta = this.beta;
  14257. this._cache.radius = this.radius;
  14258. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14259. };
  14260. ArcRotateCamera.prototype._getTargetPosition = function () {
  14261. if (this.target.getAbsolutePosition) {
  14262. return this.target.getAbsolutePosition();
  14263. }
  14264. return this.target;
  14265. };
  14266. // Synchronized
  14267. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14268. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14269. return false;
  14270. return this._cache.target.equals(this.target)
  14271. && this._cache.alpha === this.alpha
  14272. && this._cache.beta === this.beta
  14273. && this._cache.radius === this.radius
  14274. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14275. };
  14276. // Methods
  14277. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  14278. var _this = this;
  14279. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14280. this._useCtrlForPanning = useCtrlForPanning;
  14281. this.inputs.attachElement(element, noPreventDefault);
  14282. this._reset = function () {
  14283. _this.inertialAlphaOffset = 0;
  14284. _this.inertialBetaOffset = 0;
  14285. _this.inertialRadiusOffset = 0;
  14286. };
  14287. };
  14288. ArcRotateCamera.prototype.detachControl = function (element) {
  14289. this.inputs.detachElement(element);
  14290. if (this._reset) {
  14291. this._reset();
  14292. }
  14293. };
  14294. ArcRotateCamera.prototype._checkInputs = function () {
  14295. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14296. if (this._collisionTriggered) {
  14297. return;
  14298. }
  14299. this.inputs.checkInputs();
  14300. // Inertia
  14301. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14302. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14303. this.beta += this.inertialBetaOffset;
  14304. this.radius -= this.inertialRadiusOffset;
  14305. this.inertialAlphaOffset *= this.inertia;
  14306. this.inertialBetaOffset *= this.inertia;
  14307. this.inertialRadiusOffset *= this.inertia;
  14308. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14309. this.inertialAlphaOffset = 0;
  14310. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14311. this.inertialBetaOffset = 0;
  14312. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14313. this.inertialRadiusOffset = 0;
  14314. }
  14315. // Panning inertia
  14316. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14317. if (!this._localDirection) {
  14318. this._localDirection = BABYLON.Vector3.Zero();
  14319. this._transformedDirection = BABYLON.Vector3.Zero();
  14320. }
  14321. this.inertialPanningX *= this.inertia;
  14322. this.inertialPanningY *= this.inertia;
  14323. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14324. this.inertialPanningX = 0;
  14325. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14326. this.inertialPanningY = 0;
  14327. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14328. this._localDirection.multiplyInPlace(this.panningAxis);
  14329. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14330. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14331. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14332. if (!this.panningAxis.y) {
  14333. this._transformedDirection.y = 0;
  14334. }
  14335. if (!this.target.getAbsolutePosition) {
  14336. this.target.addInPlace(this._transformedDirection);
  14337. }
  14338. }
  14339. // Limits
  14340. this._checkLimits();
  14341. _super.prototype._checkInputs.call(this);
  14342. };
  14343. ArcRotateCamera.prototype._checkLimits = function () {
  14344. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14345. if (this.allowUpsideDown && this.beta > Math.PI) {
  14346. this.beta = this.beta - (2 * Math.PI);
  14347. }
  14348. }
  14349. else {
  14350. if (this.beta < this.lowerBetaLimit) {
  14351. this.beta = this.lowerBetaLimit;
  14352. }
  14353. }
  14354. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14355. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14356. this.beta = this.beta + (2 * Math.PI);
  14357. }
  14358. }
  14359. else {
  14360. if (this.beta > this.upperBetaLimit) {
  14361. this.beta = this.upperBetaLimit;
  14362. }
  14363. }
  14364. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14365. this.alpha = this.lowerAlphaLimit;
  14366. }
  14367. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14368. this.alpha = this.upperAlphaLimit;
  14369. }
  14370. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14371. this.radius = this.lowerRadiusLimit;
  14372. }
  14373. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14374. this.radius = this.upperRadiusLimit;
  14375. }
  14376. };
  14377. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14378. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14379. this.radius = radiusv3.length();
  14380. // Alpha
  14381. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14382. if (radiusv3.z < 0) {
  14383. this.alpha = 2 * Math.PI - this.alpha;
  14384. }
  14385. // Beta
  14386. this.beta = Math.acos(radiusv3.y / this.radius);
  14387. this._checkLimits();
  14388. };
  14389. ArcRotateCamera.prototype.setPosition = function (position) {
  14390. if (this.position.equals(position)) {
  14391. return;
  14392. }
  14393. this.position = position;
  14394. this.rebuildAnglesAndRadius();
  14395. };
  14396. ArcRotateCamera.prototype.setTarget = function (target) {
  14397. if (this._getTargetPosition().equals(target)) {
  14398. return;
  14399. }
  14400. this.target = target;
  14401. this.rebuildAnglesAndRadius();
  14402. };
  14403. ArcRotateCamera.prototype._getViewMatrix = function () {
  14404. // Compute
  14405. var cosa = Math.cos(this.alpha);
  14406. var sina = Math.sin(this.alpha);
  14407. var cosb = Math.cos(this.beta);
  14408. var sinb = Math.sin(this.beta);
  14409. if (sinb === 0) {
  14410. sinb = 0.0001;
  14411. }
  14412. var target = this._getTargetPosition();
  14413. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14414. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14415. this._collider.radius = this.collisionRadius;
  14416. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14417. this._collisionTriggered = true;
  14418. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14419. }
  14420. else {
  14421. this.position.copyFrom(this._newPosition);
  14422. var up = this.upVector;
  14423. if (this.allowUpsideDown && this.beta < 0) {
  14424. up = up.clone();
  14425. up = up.negate();
  14426. }
  14427. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14428. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14429. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14430. }
  14431. return this._viewMatrix;
  14432. };
  14433. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14434. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14435. meshes = meshes || this.getScene().meshes;
  14436. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14437. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14438. this.radius = distance * this.zoomOnFactor;
  14439. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14440. };
  14441. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14442. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14443. var meshesOrMinMaxVector;
  14444. var distance;
  14445. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14446. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14447. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14448. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14449. }
  14450. else {
  14451. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14452. distance = meshesOrMinMaxVectorAndDistance.distance;
  14453. }
  14454. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14455. if (!doNotUpdateMaxZ) {
  14456. this.maxZ = distance * 2;
  14457. }
  14458. };
  14459. /**
  14460. * @override
  14461. * Override Camera.createRigCamera
  14462. */
  14463. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14464. var alphaShift;
  14465. switch (this.cameraRigMode) {
  14466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14468. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14469. case BABYLON.Camera.RIG_MODE_VR:
  14470. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14471. break;
  14472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14473. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14474. break;
  14475. }
  14476. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14477. rigCam._cameraRigParams = {};
  14478. return rigCam;
  14479. };
  14480. /**
  14481. * @override
  14482. * Override Camera._updateRigCameras
  14483. */
  14484. ArcRotateCamera.prototype._updateRigCameras = function () {
  14485. var camLeft = this._rigCameras[0];
  14486. var camRight = this._rigCameras[1];
  14487. camLeft.beta = camRight.beta = this.beta;
  14488. camLeft.radius = camRight.radius = this.radius;
  14489. switch (this.cameraRigMode) {
  14490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14491. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14493. case BABYLON.Camera.RIG_MODE_VR:
  14494. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14495. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14496. break;
  14497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14498. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14499. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14500. break;
  14501. }
  14502. _super.prototype._updateRigCameras.call(this);
  14503. };
  14504. ArcRotateCamera.prototype.dispose = function () {
  14505. this.inputs.clear();
  14506. _super.prototype.dispose.call(this);
  14507. };
  14508. ArcRotateCamera.prototype.getTypeName = function () {
  14509. return "ArcRotateCamera";
  14510. };
  14511. __decorate([
  14512. BABYLON.serialize()
  14513. ], ArcRotateCamera.prototype, "alpha", void 0);
  14514. __decorate([
  14515. BABYLON.serialize()
  14516. ], ArcRotateCamera.prototype, "beta", void 0);
  14517. __decorate([
  14518. BABYLON.serialize()
  14519. ], ArcRotateCamera.prototype, "radius", void 0);
  14520. __decorate([
  14521. BABYLON.serializeAsVector3()
  14522. ], ArcRotateCamera.prototype, "target", void 0);
  14523. __decorate([
  14524. BABYLON.serialize()
  14525. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14526. __decorate([
  14527. BABYLON.serialize()
  14528. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14529. __decorate([
  14530. BABYLON.serialize()
  14531. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14532. __decorate([
  14533. BABYLON.serialize()
  14534. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14535. __decorate([
  14536. BABYLON.serialize()
  14537. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14538. __decorate([
  14539. BABYLON.serialize()
  14540. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14541. __decorate([
  14542. BABYLON.serialize()
  14543. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14544. __decorate([
  14545. BABYLON.serialize()
  14546. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14547. __decorate([
  14548. BABYLON.serialize()
  14549. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14550. __decorate([
  14551. BABYLON.serialize()
  14552. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14553. __decorate([
  14554. BABYLON.serialize()
  14555. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14556. __decorate([
  14557. BABYLON.serialize()
  14558. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14559. __decorate([
  14560. BABYLON.serialize()
  14561. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14562. return ArcRotateCamera;
  14563. })(BABYLON.TargetCamera);
  14564. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14565. })(BABYLON || (BABYLON = {}));
  14566. var BABYLON;
  14567. (function (BABYLON) {
  14568. var ArcRotateCameraInputsManager = (function (_super) {
  14569. __extends(ArcRotateCameraInputsManager, _super);
  14570. function ArcRotateCameraInputsManager(camera) {
  14571. _super.call(this, camera);
  14572. }
  14573. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14574. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14575. return this;
  14576. };
  14577. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14578. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14579. return this;
  14580. };
  14581. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14582. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14583. return this;
  14584. };
  14585. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14586. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14587. return this;
  14588. };
  14589. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14590. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14591. return this;
  14592. };
  14593. return ArcRotateCameraInputsManager;
  14594. })(BABYLON.CameraInputsManager);
  14595. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14596. })(BABYLON || (BABYLON = {}));
  14597. var BABYLON;
  14598. (function (BABYLON) {
  14599. var RenderingManager = (function () {
  14600. function RenderingManager(scene) {
  14601. this._renderingGroups = new Array();
  14602. this._scene = scene;
  14603. }
  14604. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14605. if (this._scene._activeParticleSystems.length === 0) {
  14606. return;
  14607. }
  14608. // Particles
  14609. var activeCamera = this._scene.activeCamera;
  14610. this._scene._particlesDuration.beginMonitoring();
  14611. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14612. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14613. if (particleSystem.renderingGroupId !== index) {
  14614. continue;
  14615. }
  14616. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14617. continue;
  14618. }
  14619. this._clearDepthBuffer();
  14620. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14621. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14622. }
  14623. }
  14624. this._scene._particlesDuration.endMonitoring(false);
  14625. };
  14626. RenderingManager.prototype._renderSprites = function (index) {
  14627. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14628. return;
  14629. }
  14630. // Sprites
  14631. var activeCamera = this._scene.activeCamera;
  14632. this._scene._spritesDuration.beginMonitoring();
  14633. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14634. var spriteManager = this._scene.spriteManagers[id];
  14635. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14636. this._clearDepthBuffer();
  14637. spriteManager.render();
  14638. }
  14639. }
  14640. this._scene._spritesDuration.endMonitoring(false);
  14641. };
  14642. RenderingManager.prototype._clearDepthBuffer = function () {
  14643. if (this._depthBufferAlreadyCleaned) {
  14644. return;
  14645. }
  14646. this._scene.getEngine().clear(0, false, true);
  14647. this._depthBufferAlreadyCleaned = true;
  14648. };
  14649. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14650. if (this._currentRenderSprites) {
  14651. this._renderSprites(this._currentIndex);
  14652. }
  14653. if (this._currentRenderParticles) {
  14654. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14655. }
  14656. };
  14657. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14658. this._currentActiveMeshes = activeMeshes;
  14659. this._currentRenderParticles = renderParticles;
  14660. this._currentRenderSprites = renderSprites;
  14661. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14662. this._depthBufferAlreadyCleaned = index == 0;
  14663. var renderingGroup = this._renderingGroups[index];
  14664. var needToStepBack = false;
  14665. this._currentIndex = index;
  14666. if (renderingGroup) {
  14667. this._clearDepthBuffer();
  14668. if (!renderingGroup.onBeforeTransparentRendering) {
  14669. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14670. }
  14671. if (!renderingGroup.render(customRenderFunction)) {
  14672. this._renderingGroups.splice(index, 1);
  14673. needToStepBack = true;
  14674. this._renderSpritesAndParticles();
  14675. }
  14676. }
  14677. else {
  14678. this._renderSpritesAndParticles();
  14679. }
  14680. if (needToStepBack) {
  14681. index--;
  14682. }
  14683. }
  14684. };
  14685. RenderingManager.prototype.reset = function () {
  14686. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14687. if (renderingGroup) {
  14688. renderingGroup.prepare();
  14689. }
  14690. });
  14691. };
  14692. RenderingManager.prototype.dispatch = function (subMesh) {
  14693. var mesh = subMesh.getMesh();
  14694. var renderingGroupId = mesh.renderingGroupId || 0;
  14695. if (!this._renderingGroups[renderingGroupId]) {
  14696. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14697. }
  14698. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14699. };
  14700. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14701. return RenderingManager;
  14702. })();
  14703. BABYLON.RenderingManager = RenderingManager;
  14704. })(BABYLON || (BABYLON = {}));
  14705. var BABYLON;
  14706. (function (BABYLON) {
  14707. var RenderingGroup = (function () {
  14708. function RenderingGroup(index, scene) {
  14709. this.index = index;
  14710. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14711. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14712. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14713. this._scene = scene;
  14714. }
  14715. RenderingGroup.prototype.render = function (customRenderFunction) {
  14716. if (customRenderFunction) {
  14717. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14718. return true;
  14719. }
  14720. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14721. if (this.onBeforeTransparentRendering) {
  14722. this.onBeforeTransparentRendering();
  14723. }
  14724. return false;
  14725. }
  14726. var engine = this._scene.getEngine();
  14727. // Opaque
  14728. var subIndex;
  14729. var submesh;
  14730. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14731. submesh = this._opaqueSubMeshes.data[subIndex];
  14732. submesh.render(false);
  14733. }
  14734. // Alpha test
  14735. engine.setAlphaTesting(true);
  14736. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14737. submesh = this._alphaTestSubMeshes.data[subIndex];
  14738. submesh.render(false);
  14739. }
  14740. engine.setAlphaTesting(false);
  14741. if (this.onBeforeTransparentRendering) {
  14742. this.onBeforeTransparentRendering();
  14743. }
  14744. // Transparent
  14745. if (this._transparentSubMeshes.length) {
  14746. // Sorting
  14747. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14748. submesh = this._transparentSubMeshes.data[subIndex];
  14749. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14750. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14751. }
  14752. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14753. sortedArray.sort(function (a, b) {
  14754. // Alpha index first
  14755. if (a._alphaIndex > b._alphaIndex) {
  14756. return 1;
  14757. }
  14758. if (a._alphaIndex < b._alphaIndex) {
  14759. return -1;
  14760. }
  14761. // Then distance to camera
  14762. if (a._distanceToCamera < b._distanceToCamera) {
  14763. return 1;
  14764. }
  14765. if (a._distanceToCamera > b._distanceToCamera) {
  14766. return -1;
  14767. }
  14768. return 0;
  14769. });
  14770. // Rendering
  14771. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14772. submesh = sortedArray[subIndex];
  14773. submesh.render(true);
  14774. }
  14775. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14776. }
  14777. return true;
  14778. };
  14779. RenderingGroup.prototype.prepare = function () {
  14780. this._opaqueSubMeshes.reset();
  14781. this._transparentSubMeshes.reset();
  14782. this._alphaTestSubMeshes.reset();
  14783. };
  14784. RenderingGroup.prototype.dispatch = function (subMesh) {
  14785. var material = subMesh.getMaterial();
  14786. var mesh = subMesh.getMesh();
  14787. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14788. this._transparentSubMeshes.push(subMesh);
  14789. }
  14790. else if (material.needAlphaTesting()) {
  14791. this._alphaTestSubMeshes.push(subMesh);
  14792. }
  14793. else {
  14794. this._opaqueSubMeshes.push(subMesh); // Opaque
  14795. }
  14796. };
  14797. return RenderingGroup;
  14798. })();
  14799. BABYLON.RenderingGroup = RenderingGroup;
  14800. })(BABYLON || (BABYLON = {}));
  14801. var BABYLON;
  14802. (function (BABYLON) {
  14803. var PointerEventTypes = (function () {
  14804. function PointerEventTypes() {
  14805. }
  14806. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14807. get: function () {
  14808. return PointerEventTypes._POINTERDOWN;
  14809. },
  14810. enumerable: true,
  14811. configurable: true
  14812. });
  14813. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14814. get: function () {
  14815. return PointerEventTypes._POINTERUP;
  14816. },
  14817. enumerable: true,
  14818. configurable: true
  14819. });
  14820. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14821. get: function () {
  14822. return PointerEventTypes._POINTERMOVE;
  14823. },
  14824. enumerable: true,
  14825. configurable: true
  14826. });
  14827. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14828. get: function () {
  14829. return PointerEventTypes._POINTERWHEEL;
  14830. },
  14831. enumerable: true,
  14832. configurable: true
  14833. });
  14834. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14835. get: function () {
  14836. return PointerEventTypes._POINTERPICK;
  14837. },
  14838. enumerable: true,
  14839. configurable: true
  14840. });
  14841. PointerEventTypes._POINTERDOWN = 0x01;
  14842. PointerEventTypes._POINTERUP = 0x02;
  14843. PointerEventTypes._POINTERMOVE = 0x04;
  14844. PointerEventTypes._POINTERWHEEL = 0x08;
  14845. PointerEventTypes._POINTERPICK = 0x10;
  14846. return PointerEventTypes;
  14847. })();
  14848. BABYLON.PointerEventTypes = PointerEventTypes;
  14849. var PointerInfoBase = (function () {
  14850. function PointerInfoBase(type, event) {
  14851. this.type = type;
  14852. this.event = event;
  14853. }
  14854. return PointerInfoBase;
  14855. })();
  14856. BABYLON.PointerInfoBase = PointerInfoBase;
  14857. /**
  14858. * This class is used to store pointer related info for the onPrePointerObservable event.
  14859. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14860. */
  14861. var PointerInfoPre = (function (_super) {
  14862. __extends(PointerInfoPre, _super);
  14863. function PointerInfoPre(type, event, localX, localY) {
  14864. _super.call(this, type, event);
  14865. this.skipOnPointerObservable = false;
  14866. this.localPosition = new BABYLON.Vector2(localX, localY);
  14867. }
  14868. return PointerInfoPre;
  14869. })(PointerInfoBase);
  14870. BABYLON.PointerInfoPre = PointerInfoPre;
  14871. /**
  14872. * This type contains all the data related to a pointer event in Babylon.js.
  14873. * 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.
  14874. */
  14875. var PointerInfo = (function (_super) {
  14876. __extends(PointerInfo, _super);
  14877. function PointerInfo(type, event, pickInfo) {
  14878. _super.call(this, type, event);
  14879. this.pickInfo = pickInfo;
  14880. }
  14881. return PointerInfo;
  14882. })(PointerInfoBase);
  14883. BABYLON.PointerInfo = PointerInfo;
  14884. /**
  14885. * Represents a scene to be rendered by the engine.
  14886. * @see http://doc.babylonjs.com/page.php?p=21911
  14887. */
  14888. var Scene = (function () {
  14889. /**
  14890. * @constructor
  14891. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14892. */
  14893. function Scene(engine) {
  14894. // Members
  14895. this.autoClear = true;
  14896. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14897. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14898. this.forceWireframe = false;
  14899. this.forcePointsCloud = false;
  14900. this.forceShowBoundingBoxes = false;
  14901. this.animationsEnabled = true;
  14902. this.constantlyUpdateMeshUnderPointer = false;
  14903. this.hoverCursor = "pointer";
  14904. // Events
  14905. /**
  14906. * An event triggered when the scene is disposed.
  14907. * @type {BABYLON.Observable}
  14908. */
  14909. this.onDisposeObservable = new BABYLON.Observable();
  14910. /**
  14911. * An event triggered before rendering the scene
  14912. * @type {BABYLON.Observable}
  14913. */
  14914. this.onBeforeRenderObservable = new BABYLON.Observable();
  14915. /**
  14916. * An event triggered after rendering the scene
  14917. * @type {BABYLON.Observable}
  14918. */
  14919. this.onAfterRenderObservable = new BABYLON.Observable();
  14920. /**
  14921. * An event triggered when the scene is ready
  14922. * @type {BABYLON.Observable}
  14923. */
  14924. this.onReadyObservable = new BABYLON.Observable();
  14925. /**
  14926. * An event triggered before rendering a camera
  14927. * @type {BABYLON.Observable}
  14928. */
  14929. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14930. /**
  14931. * An event triggered after rendering a camera
  14932. * @type {BABYLON.Observable}
  14933. */
  14934. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14935. /**
  14936. * An event triggered when a camera is created
  14937. * @type {BABYLON.Observable}
  14938. */
  14939. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14940. /**
  14941. * An event triggered when a camera is removed
  14942. * @type {BABYLON.Observable}
  14943. */
  14944. this.onCameraRemovedObservable = new BABYLON.Observable();
  14945. /**
  14946. * An event triggered when a light is created
  14947. * @type {BABYLON.Observable}
  14948. */
  14949. this.onNewLightAddedObservable = new BABYLON.Observable();
  14950. /**
  14951. * An event triggered when a light is removed
  14952. * @type {BABYLON.Observable}
  14953. */
  14954. this.onLightRemovedObservable = new BABYLON.Observable();
  14955. /**
  14956. * An event triggered when a geometry is created
  14957. * @type {BABYLON.Observable}
  14958. */
  14959. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14960. /**
  14961. * An event triggered when a geometry is removed
  14962. * @type {BABYLON.Observable}
  14963. */
  14964. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14965. /**
  14966. * An event triggered when a mesh is created
  14967. * @type {BABYLON.Observable}
  14968. */
  14969. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14970. /**
  14971. * An event triggered when a mesh is removed
  14972. * @type {BABYLON.Observable}
  14973. */
  14974. this.onMeshRemovedObservable = new BABYLON.Observable();
  14975. // Animations
  14976. this.animations = [];
  14977. /**
  14978. * 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).
  14979. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14980. */
  14981. this.onPrePointerObservable = new BABYLON.Observable();
  14982. /**
  14983. * Observable event triggered each time an input event is received from the rendering canvas
  14984. */
  14985. this.onPointerObservable = new BABYLON.Observable();
  14986. 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
  14987. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14988. this._startingPointerTime = 0;
  14989. // Fog
  14990. /**
  14991. * is fog enabled on this scene.
  14992. * @type {boolean}
  14993. */
  14994. this.fogEnabled = true;
  14995. this.fogMode = Scene.FOGMODE_NONE;
  14996. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14997. this.fogDensity = 0.1;
  14998. this.fogStart = 0;
  14999. this.fogEnd = 1000.0;
  15000. // Lights
  15001. /**
  15002. * is shadow enabled on this scene.
  15003. * @type {boolean}
  15004. */
  15005. this.shadowsEnabled = true;
  15006. /**
  15007. * is light enabled on this scene.
  15008. * @type {boolean}
  15009. */
  15010. this.lightsEnabled = true;
  15011. /**
  15012. * All of the lights added to this scene.
  15013. * @see BABYLON.Light
  15014. * @type {BABYLON.Light[]}
  15015. */
  15016. this.lights = new Array();
  15017. // Cameras
  15018. /**
  15019. * All of the cameras added to this scene.
  15020. * @see BABYLON.Camera
  15021. * @type {BABYLON.Camera[]}
  15022. */
  15023. this.cameras = new Array();
  15024. this.activeCameras = new Array();
  15025. // Meshes
  15026. /**
  15027. * All of the (abstract) meshes added to this scene.
  15028. * @see BABYLON.AbstractMesh
  15029. * @type {BABYLON.AbstractMesh[]}
  15030. */
  15031. this.meshes = new Array();
  15032. // Geometries
  15033. this._geometries = new Array();
  15034. this.materials = new Array();
  15035. this.multiMaterials = new Array();
  15036. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15037. // Textures
  15038. this.texturesEnabled = true;
  15039. this.textures = new Array();
  15040. // Particles
  15041. this.particlesEnabled = true;
  15042. this.particleSystems = new Array();
  15043. // Sprites
  15044. this.spritesEnabled = true;
  15045. this.spriteManagers = new Array();
  15046. // Layers
  15047. this.layers = new Array();
  15048. // Skeletons
  15049. this.skeletonsEnabled = true;
  15050. this.skeletons = new Array();
  15051. // Lens flares
  15052. this.lensFlaresEnabled = true;
  15053. this.lensFlareSystems = new Array();
  15054. // Collisions
  15055. this.collisionsEnabled = true;
  15056. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15057. // Postprocesses
  15058. this.postProcessesEnabled = true;
  15059. // Customs render targets
  15060. this.renderTargetsEnabled = true;
  15061. this.dumpNextRenderTargets = false;
  15062. this.customRenderTargets = new Array();
  15063. // Imported meshes
  15064. this.importedMeshesFiles = new Array();
  15065. // Probes
  15066. this.probesEnabled = true;
  15067. this.reflectionProbes = new Array();
  15068. this._actionManagers = new Array();
  15069. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15070. // Procedural textures
  15071. this.proceduralTexturesEnabled = true;
  15072. this._proceduralTextures = new Array();
  15073. this.soundTracks = new Array();
  15074. this._audioEnabled = true;
  15075. this._headphone = false;
  15076. // Performance counters
  15077. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15078. this._totalLightsCounter = new BABYLON.PerfCounter();
  15079. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15080. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15081. this._totalVertices = new BABYLON.PerfCounter();
  15082. this._activeIndices = new BABYLON.PerfCounter();
  15083. this._activeParticles = new BABYLON.PerfCounter();
  15084. this._lastFrameDuration = new BABYLON.PerfCounter();
  15085. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15086. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15087. this._particlesDuration = new BABYLON.PerfCounter();
  15088. this._renderDuration = new BABYLON.PerfCounter();
  15089. this._spritesDuration = new BABYLON.PerfCounter();
  15090. this._activeBones = new BABYLON.PerfCounter();
  15091. this._renderId = 0;
  15092. this._executeWhenReadyTimeoutId = -1;
  15093. this._intermediateRendering = false;
  15094. this._toBeDisposed = new BABYLON.SmartArray(256);
  15095. this._pendingData = []; //ANY
  15096. this._activeMeshes = new BABYLON.SmartArray(256);
  15097. this._processedMaterials = new BABYLON.SmartArray(256);
  15098. this._renderTargets = new BABYLON.SmartArray(256);
  15099. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15100. this._activeSkeletons = new BABYLON.SmartArray(32);
  15101. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15102. this._activeAnimatables = new Array();
  15103. this._transformMatrix = BABYLON.Matrix.Zero();
  15104. this._edgesRenderers = new BABYLON.SmartArray(16);
  15105. this._uniqueIdCounter = 0;
  15106. this._engine = engine;
  15107. engine.scenes.push(this);
  15108. this._renderingManager = new BABYLON.RenderingManager(this);
  15109. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15110. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15111. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15112. if (BABYLON.OutlineRenderer) {
  15113. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15114. }
  15115. this.attachControl();
  15116. if (BABYLON.SoundTrack) {
  15117. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15118. }
  15119. //simplification queue
  15120. if (BABYLON.SimplificationQueue) {
  15121. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15122. }
  15123. //collision coordinator initialization. For now legacy per default.
  15124. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15125. }
  15126. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15127. get: function () {
  15128. return Scene._FOGMODE_NONE;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15134. get: function () {
  15135. return Scene._FOGMODE_EXP;
  15136. },
  15137. enumerable: true,
  15138. configurable: true
  15139. });
  15140. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15141. get: function () {
  15142. return Scene._FOGMODE_EXP2;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15148. get: function () {
  15149. return Scene._FOGMODE_LINEAR;
  15150. },
  15151. enumerable: true,
  15152. configurable: true
  15153. });
  15154. Object.defineProperty(Scene.prototype, "onDispose", {
  15155. set: function (callback) {
  15156. if (this._onDisposeObserver) {
  15157. this.onDisposeObservable.remove(this._onDisposeObserver);
  15158. }
  15159. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. Object.defineProperty(Scene.prototype, "beforeRender", {
  15165. set: function (callback) {
  15166. if (this._onBeforeRenderObserver) {
  15167. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15168. }
  15169. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15170. },
  15171. enumerable: true,
  15172. configurable: true
  15173. });
  15174. Object.defineProperty(Scene.prototype, "afterRender", {
  15175. set: function (callback) {
  15176. if (this._onAfterRenderObserver) {
  15177. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15178. }
  15179. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15180. },
  15181. enumerable: true,
  15182. configurable: true
  15183. });
  15184. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15185. set: function (callback) {
  15186. if (this._onBeforeCameraRenderObserver) {
  15187. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15188. }
  15189. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15195. set: function (callback) {
  15196. if (this._onAfterCameraRenderObserver) {
  15197. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15198. }
  15199. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15200. },
  15201. enumerable: true,
  15202. configurable: true
  15203. });
  15204. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15205. get: function () {
  15206. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15207. },
  15208. enumerable: true,
  15209. configurable: true
  15210. });
  15211. Object.defineProperty(Scene.prototype, "debugLayer", {
  15212. // Properties
  15213. get: function () {
  15214. if (!this._debugLayer) {
  15215. this._debugLayer = new BABYLON.DebugLayer(this);
  15216. }
  15217. return this._debugLayer;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15223. get: function () {
  15224. return this._workerCollisions;
  15225. },
  15226. set: function (enabled) {
  15227. enabled = (enabled && !!Worker);
  15228. this._workerCollisions = enabled;
  15229. if (this.collisionCoordinator) {
  15230. this.collisionCoordinator.destroy();
  15231. }
  15232. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15233. this.collisionCoordinator.init(this);
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15239. get: function () {
  15240. return this._selectionOctree;
  15241. },
  15242. enumerable: true,
  15243. configurable: true
  15244. });
  15245. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15246. /**
  15247. * The mesh that is currently under the pointer.
  15248. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15249. */
  15250. get: function () {
  15251. return this._pointerOverMesh;
  15252. },
  15253. enumerable: true,
  15254. configurable: true
  15255. });
  15256. Object.defineProperty(Scene.prototype, "pointerX", {
  15257. /**
  15258. * Current on-screen X position of the pointer
  15259. * @return {number} X position of the pointer
  15260. */
  15261. get: function () {
  15262. return this._pointerX;
  15263. },
  15264. enumerable: true,
  15265. configurable: true
  15266. });
  15267. Object.defineProperty(Scene.prototype, "pointerY", {
  15268. /**
  15269. * Current on-screen Y position of the pointer
  15270. * @return {number} Y position of the pointer
  15271. */
  15272. get: function () {
  15273. return this._pointerY;
  15274. },
  15275. enumerable: true,
  15276. configurable: true
  15277. });
  15278. Scene.prototype.getCachedMaterial = function () {
  15279. return this._cachedMaterial;
  15280. };
  15281. Scene.prototype.getBoundingBoxRenderer = function () {
  15282. return this._boundingBoxRenderer;
  15283. };
  15284. Scene.prototype.getOutlineRenderer = function () {
  15285. return this._outlineRenderer;
  15286. };
  15287. Scene.prototype.getEngine = function () {
  15288. return this._engine;
  15289. };
  15290. Scene.prototype.getTotalVertices = function () {
  15291. return this._totalVertices.current;
  15292. };
  15293. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15294. get: function () {
  15295. return this._totalVertices;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Scene.prototype.getActiveIndices = function () {
  15301. return this._activeIndices.current;
  15302. };
  15303. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15304. get: function () {
  15305. return this._activeIndices;
  15306. },
  15307. enumerable: true,
  15308. configurable: true
  15309. });
  15310. Scene.prototype.getActiveParticles = function () {
  15311. return this._activeParticles.current;
  15312. };
  15313. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15314. get: function () {
  15315. return this._activeParticles;
  15316. },
  15317. enumerable: true,
  15318. configurable: true
  15319. });
  15320. Scene.prototype.getActiveBones = function () {
  15321. return this._activeBones.current;
  15322. };
  15323. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15324. get: function () {
  15325. return this._activeBones;
  15326. },
  15327. enumerable: true,
  15328. configurable: true
  15329. });
  15330. // Stats
  15331. Scene.prototype.getLastFrameDuration = function () {
  15332. return this._lastFrameDuration.current;
  15333. };
  15334. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15335. get: function () {
  15336. return this._lastFrameDuration;
  15337. },
  15338. enumerable: true,
  15339. configurable: true
  15340. });
  15341. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15342. return this._evaluateActiveMeshesDuration.current;
  15343. };
  15344. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15345. get: function () {
  15346. return this._evaluateActiveMeshesDuration;
  15347. },
  15348. enumerable: true,
  15349. configurable: true
  15350. });
  15351. Scene.prototype.getActiveMeshes = function () {
  15352. return this._activeMeshes;
  15353. };
  15354. Scene.prototype.getRenderTargetsDuration = function () {
  15355. return this._renderTargetsDuration.current;
  15356. };
  15357. Scene.prototype.getRenderDuration = function () {
  15358. return this._renderDuration.current;
  15359. };
  15360. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15361. get: function () {
  15362. return this._renderDuration;
  15363. },
  15364. enumerable: true,
  15365. configurable: true
  15366. });
  15367. Scene.prototype.getParticlesDuration = function () {
  15368. return this._particlesDuration.current;
  15369. };
  15370. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15371. get: function () {
  15372. return this._particlesDuration;
  15373. },
  15374. enumerable: true,
  15375. configurable: true
  15376. });
  15377. Scene.prototype.getSpritesDuration = function () {
  15378. return this._spritesDuration.current;
  15379. };
  15380. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15381. get: function () {
  15382. return this._spritesDuration;
  15383. },
  15384. enumerable: true,
  15385. configurable: true
  15386. });
  15387. Scene.prototype.getAnimationRatio = function () {
  15388. return this._animationRatio;
  15389. };
  15390. Scene.prototype.getRenderId = function () {
  15391. return this._renderId;
  15392. };
  15393. Scene.prototype.incrementRenderId = function () {
  15394. this._renderId++;
  15395. };
  15396. Scene.prototype._updatePointerPosition = function (evt) {
  15397. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15398. this._pointerX = evt.clientX - canvasRect.left;
  15399. this._pointerY = evt.clientY - canvasRect.top;
  15400. this._unTranslatedPointerX = this._pointerX;
  15401. this._unTranslatedPointerY = this._pointerY;
  15402. if (this.cameraToUseForPointers) {
  15403. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15404. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15405. }
  15406. };
  15407. // Pointers handling
  15408. /**
  15409. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15410. * @param attachUp defines if you want to attach events to pointerup
  15411. * @param attachDown defines if you want to attach events to pointerdown
  15412. * @param attachMove defines if you want to attach events to pointermove
  15413. */
  15414. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15415. var _this = this;
  15416. if (attachUp === void 0) { attachUp = true; }
  15417. if (attachDown === void 0) { attachDown = true; }
  15418. if (attachMove === void 0) { attachMove = true; }
  15419. var spritePredicate = function (sprite) {
  15420. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15421. };
  15422. this._onPointerMove = function (evt) {
  15423. _this._updatePointerPosition(evt);
  15424. // PreObservable support
  15425. if (_this.onPrePointerObservable.hasObservers()) {
  15426. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15427. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15428. _this.onPrePointerObservable.notifyObservers(pi, type);
  15429. if (pi.skipOnPointerObservable) {
  15430. return;
  15431. }
  15432. }
  15433. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15434. return;
  15435. }
  15436. var canvas = _this._engine.getRenderingCanvas();
  15437. if (!_this.pointerMovePredicate) {
  15438. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15439. }
  15440. // Meshes
  15441. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15442. if (pickResult.hit && pickResult.pickedMesh) {
  15443. _this.setPointerOverSprite(null);
  15444. _this.setPointerOverMesh(pickResult.pickedMesh);
  15445. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15446. canvas.style.cursor = _this.hoverCursor;
  15447. }
  15448. else {
  15449. canvas.style.cursor = "";
  15450. }
  15451. }
  15452. else {
  15453. _this.setPointerOverMesh(null);
  15454. // Sprites
  15455. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15456. if (pickResult.hit && pickResult.pickedSprite) {
  15457. canvas.style.cursor = _this.hoverCursor;
  15458. _this.setPointerOverSprite(pickResult.pickedSprite);
  15459. }
  15460. else {
  15461. _this.setPointerOverSprite(null);
  15462. // Restore pointer
  15463. canvas.style.cursor = "";
  15464. }
  15465. }
  15466. if (_this.onPointerMove) {
  15467. _this.onPointerMove(evt, pickResult);
  15468. }
  15469. if (_this.onPointerObservable.hasObservers()) {
  15470. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15471. var pi = new PointerInfo(type, evt, pickResult);
  15472. _this.onPointerObservable.notifyObservers(pi, type);
  15473. }
  15474. };
  15475. this._onPointerDown = function (evt) {
  15476. _this._updatePointerPosition(evt);
  15477. // PreObservable support
  15478. if (_this.onPrePointerObservable.hasObservers()) {
  15479. var type = PointerEventTypes.POINTERDOWN;
  15480. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15481. _this.onPrePointerObservable.notifyObservers(pi, type);
  15482. if (pi.skipOnPointerObservable) {
  15483. return;
  15484. }
  15485. }
  15486. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15487. return;
  15488. }
  15489. _this._startingPointerPosition.x = _this._pointerX;
  15490. _this._startingPointerPosition.y = _this._pointerY;
  15491. _this._startingPointerTime = new Date().getTime();
  15492. if (!_this.pointerDownPredicate) {
  15493. _this.pointerDownPredicate = function (mesh) {
  15494. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15495. };
  15496. }
  15497. // Meshes
  15498. _this._pickedDownMesh = null;
  15499. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15500. if (pickResult.hit && pickResult.pickedMesh) {
  15501. if (pickResult.pickedMesh.actionManager) {
  15502. _this._pickedDownMesh = pickResult.pickedMesh;
  15503. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15504. switch (evt.button) {
  15505. case 0:
  15506. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15507. break;
  15508. case 1:
  15509. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15510. break;
  15511. case 2:
  15512. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15513. break;
  15514. }
  15515. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15516. }
  15517. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15518. var that = _this;
  15519. window.setTimeout(function () {
  15520. 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);
  15521. if (pickResult.hit && pickResult.pickedMesh) {
  15522. if (pickResult.pickedMesh.actionManager) {
  15523. 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)) {
  15524. that._startingPointerTime = 0;
  15525. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15526. }
  15527. }
  15528. }
  15529. }, BABYLON.ActionManager.LongPressDelay);
  15530. }
  15531. }
  15532. }
  15533. if (_this.onPointerDown) {
  15534. _this.onPointerDown(evt, pickResult);
  15535. }
  15536. if (_this.onPointerObservable.hasObservers()) {
  15537. var type = PointerEventTypes.POINTERDOWN;
  15538. var pi = new PointerInfo(type, evt, pickResult);
  15539. _this.onPointerObservable.notifyObservers(pi, type);
  15540. }
  15541. // Sprites
  15542. _this._pickedDownSprite = null;
  15543. if (_this.spriteManagers.length > 0) {
  15544. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15545. if (pickResult.hit && pickResult.pickedSprite) {
  15546. if (pickResult.pickedSprite.actionManager) {
  15547. _this._pickedDownSprite = pickResult.pickedSprite;
  15548. switch (evt.button) {
  15549. case 0:
  15550. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15551. break;
  15552. case 1:
  15553. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15554. break;
  15555. case 2:
  15556. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15557. break;
  15558. }
  15559. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15560. }
  15561. }
  15562. }
  15563. };
  15564. this._onPointerUp = function (evt) {
  15565. _this._updatePointerPosition(evt);
  15566. // PreObservable support
  15567. if (_this.onPrePointerObservable.hasObservers()) {
  15568. var type = PointerEventTypes.POINTERUP;
  15569. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15570. _this.onPrePointerObservable.notifyObservers(pi, type);
  15571. if (pi.skipOnPointerObservable) {
  15572. return;
  15573. }
  15574. }
  15575. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15576. return;
  15577. }
  15578. if (!_this.pointerUpPredicate) {
  15579. _this.pointerUpPredicate = function (mesh) {
  15580. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15581. };
  15582. }
  15583. // Meshes
  15584. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15585. if (pickResult.hit && pickResult.pickedMesh) {
  15586. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15587. if (_this.onPointerPick) {
  15588. _this.onPointerPick(evt, pickResult);
  15589. }
  15590. if (_this.onPointerObservable.hasObservers()) {
  15591. var type = PointerEventTypes.POINTERPICK;
  15592. var pi = new PointerInfo(type, evt, pickResult);
  15593. _this.onPointerObservable.notifyObservers(pi, type);
  15594. }
  15595. }
  15596. if (pickResult.pickedMesh.actionManager) {
  15597. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15598. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15599. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15600. }
  15601. }
  15602. }
  15603. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15604. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15605. }
  15606. if (_this.onPointerUp) {
  15607. _this.onPointerUp(evt, pickResult);
  15608. }
  15609. if (_this.onPointerObservable.hasObservers()) {
  15610. var type = PointerEventTypes.POINTERUP;
  15611. var pi = new PointerInfo(type, evt, pickResult);
  15612. _this.onPointerObservable.notifyObservers(pi, type);
  15613. }
  15614. _this._startingPointerTime = 0;
  15615. // Sprites
  15616. if (_this.spriteManagers.length > 0) {
  15617. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15618. if (pickResult.hit && pickResult.pickedSprite) {
  15619. if (pickResult.pickedSprite.actionManager) {
  15620. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15621. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15622. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15623. }
  15624. }
  15625. }
  15626. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15627. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15628. }
  15629. }
  15630. };
  15631. this._onKeyDown = function (evt) {
  15632. if (_this.actionManager) {
  15633. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15634. }
  15635. };
  15636. this._onKeyUp = function (evt) {
  15637. if (_this.actionManager) {
  15638. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15639. }
  15640. };
  15641. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15642. var canvas = this._engine.getRenderingCanvas();
  15643. if (attachMove) {
  15644. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15645. // Wheel
  15646. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15647. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15648. }
  15649. if (attachDown) {
  15650. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15651. }
  15652. if (attachUp) {
  15653. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15654. }
  15655. canvas.tabIndex = 1;
  15656. canvas.addEventListener("keydown", this._onKeyDown, false);
  15657. canvas.addEventListener("keyup", this._onKeyUp, false);
  15658. };
  15659. Scene.prototype.detachControl = function () {
  15660. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15661. var canvas = this._engine.getRenderingCanvas();
  15662. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15663. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15664. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15665. // Wheel
  15666. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15667. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15668. canvas.removeEventListener("keydown", this._onKeyDown);
  15669. canvas.removeEventListener("keyup", this._onKeyUp);
  15670. };
  15671. // Ready
  15672. Scene.prototype.isReady = function () {
  15673. if (this._pendingData.length > 0) {
  15674. return false;
  15675. }
  15676. var index;
  15677. for (index = 0; index < this._geometries.length; index++) {
  15678. var geometry = this._geometries[index];
  15679. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15680. return false;
  15681. }
  15682. }
  15683. for (index = 0; index < this.meshes.length; index++) {
  15684. var mesh = this.meshes[index];
  15685. if (!mesh.isReady()) {
  15686. return false;
  15687. }
  15688. var mat = mesh.material;
  15689. if (mat) {
  15690. if (!mat.isReady(mesh)) {
  15691. return false;
  15692. }
  15693. }
  15694. }
  15695. return true;
  15696. };
  15697. Scene.prototype.resetCachedMaterial = function () {
  15698. this._cachedMaterial = null;
  15699. };
  15700. Scene.prototype.registerBeforeRender = function (func) {
  15701. this.onBeforeRenderObservable.add(func);
  15702. };
  15703. Scene.prototype.unregisterBeforeRender = function (func) {
  15704. this.onBeforeRenderObservable.removeCallback(func);
  15705. };
  15706. Scene.prototype.registerAfterRender = function (func) {
  15707. this.onAfterRenderObservable.add(func);
  15708. };
  15709. Scene.prototype.unregisterAfterRender = function (func) {
  15710. this.onAfterRenderObservable.removeCallback(func);
  15711. };
  15712. Scene.prototype._addPendingData = function (data) {
  15713. this._pendingData.push(data);
  15714. };
  15715. Scene.prototype._removePendingData = function (data) {
  15716. var index = this._pendingData.indexOf(data);
  15717. if (index !== -1) {
  15718. this._pendingData.splice(index, 1);
  15719. }
  15720. };
  15721. Scene.prototype.getWaitingItemsCount = function () {
  15722. return this._pendingData.length;
  15723. };
  15724. /**
  15725. * Registers a function to be executed when the scene is ready.
  15726. * @param {Function} func - the function to be executed.
  15727. */
  15728. Scene.prototype.executeWhenReady = function (func) {
  15729. var _this = this;
  15730. this.onReadyObservable.add(func);
  15731. if (this._executeWhenReadyTimeoutId !== -1) {
  15732. return;
  15733. }
  15734. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15735. _this._checkIsReady();
  15736. }, 150);
  15737. };
  15738. Scene.prototype._checkIsReady = function () {
  15739. var _this = this;
  15740. if (this.isReady()) {
  15741. this.onReadyObservable.notifyObservers(this);
  15742. this.onReadyObservable.clear();
  15743. this._executeWhenReadyTimeoutId = -1;
  15744. return;
  15745. }
  15746. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15747. _this._checkIsReady();
  15748. }, 150);
  15749. };
  15750. // Animations
  15751. /**
  15752. * Will start the animation sequence of a given target
  15753. * @param target - the target
  15754. * @param {number} from - from which frame should animation start
  15755. * @param {number} to - till which frame should animation run.
  15756. * @param {boolean} [loop] - should the animation loop
  15757. * @param {number} [speedRatio] - the speed in which to run the animation
  15758. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15759. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15760. * @return {BABYLON.Animatable} the animatable object created for this animation
  15761. * @see BABYLON.Animatable
  15762. * @see http://doc.babylonjs.com/page.php?p=22081
  15763. */
  15764. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15765. if (speedRatio === void 0) { speedRatio = 1.0; }
  15766. this.stopAnimation(target);
  15767. if (!animatable) {
  15768. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15769. }
  15770. // Local animations
  15771. if (target.animations) {
  15772. animatable.appendAnimations(target, target.animations);
  15773. }
  15774. // Children animations
  15775. if (target.getAnimatables) {
  15776. var animatables = target.getAnimatables();
  15777. for (var index = 0; index < animatables.length; index++) {
  15778. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15779. }
  15780. }
  15781. animatable.reset();
  15782. return animatable;
  15783. };
  15784. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15785. if (speedRatio === undefined) {
  15786. speedRatio = 1.0;
  15787. }
  15788. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15789. return animatable;
  15790. };
  15791. Scene.prototype.getAnimatableByTarget = function (target) {
  15792. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15793. if (this._activeAnimatables[index].target === target) {
  15794. return this._activeAnimatables[index];
  15795. }
  15796. }
  15797. return null;
  15798. };
  15799. Object.defineProperty(Scene.prototype, "Animatables", {
  15800. get: function () {
  15801. return this._activeAnimatables;
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. /**
  15807. * Will stop the animation of the given target
  15808. * @param target - the target
  15809. * @see beginAnimation
  15810. */
  15811. Scene.prototype.stopAnimation = function (target) {
  15812. var animatable = this.getAnimatableByTarget(target);
  15813. if (animatable) {
  15814. animatable.stop();
  15815. }
  15816. };
  15817. Scene.prototype._animate = function () {
  15818. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15819. return;
  15820. }
  15821. if (!this._animationStartDate) {
  15822. if (this._pendingData.length > 0) {
  15823. return;
  15824. }
  15825. this._animationStartDate = BABYLON.Tools.Now;
  15826. }
  15827. // Getting time
  15828. var now = BABYLON.Tools.Now;
  15829. var delay = now - this._animationStartDate;
  15830. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15831. this._activeAnimatables[index]._animate(delay);
  15832. }
  15833. };
  15834. // Matrix
  15835. Scene.prototype.getViewMatrix = function () {
  15836. return this._viewMatrix;
  15837. };
  15838. Scene.prototype.getProjectionMatrix = function () {
  15839. return this._projectionMatrix;
  15840. };
  15841. Scene.prototype.getTransformMatrix = function () {
  15842. return this._transformMatrix;
  15843. };
  15844. Scene.prototype.setTransformMatrix = function (view, projection) {
  15845. this._viewMatrix = view;
  15846. this._projectionMatrix = projection;
  15847. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15848. // Update frustum
  15849. if (!this._frustumPlanes) {
  15850. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15851. }
  15852. else {
  15853. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15854. }
  15855. };
  15856. // Methods
  15857. Scene.prototype.addMesh = function (newMesh) {
  15858. newMesh.uniqueId = this._uniqueIdCounter++;
  15859. var position = this.meshes.push(newMesh);
  15860. //notify the collision coordinator
  15861. this.collisionCoordinator.onMeshAdded(newMesh);
  15862. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15863. };
  15864. Scene.prototype.removeMesh = function (toRemove) {
  15865. var index = this.meshes.indexOf(toRemove);
  15866. if (index !== -1) {
  15867. // Remove from the scene if mesh found
  15868. this.meshes.splice(index, 1);
  15869. }
  15870. //notify the collision coordinator
  15871. this.collisionCoordinator.onMeshRemoved(toRemove);
  15872. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15873. return index;
  15874. };
  15875. Scene.prototype.removeSkeleton = function (toRemove) {
  15876. var index = this.skeletons.indexOf(toRemove);
  15877. if (index !== -1) {
  15878. // Remove from the scene if mesh found
  15879. this.skeletons.splice(index, 1);
  15880. }
  15881. return index;
  15882. };
  15883. Scene.prototype.removeLight = function (toRemove) {
  15884. var index = this.lights.indexOf(toRemove);
  15885. if (index !== -1) {
  15886. // Remove from the scene if mesh found
  15887. this.lights.splice(index, 1);
  15888. }
  15889. this.onLightRemovedObservable.notifyObservers(toRemove);
  15890. return index;
  15891. };
  15892. Scene.prototype.removeCamera = function (toRemove) {
  15893. var index = this.cameras.indexOf(toRemove);
  15894. if (index !== -1) {
  15895. // Remove from the scene if mesh found
  15896. this.cameras.splice(index, 1);
  15897. }
  15898. // Remove from activeCameras
  15899. var index2 = this.activeCameras.indexOf(toRemove);
  15900. if (index2 !== -1) {
  15901. // Remove from the scene if mesh found
  15902. this.activeCameras.splice(index2, 1);
  15903. }
  15904. // Reset the activeCamera
  15905. if (this.activeCamera === toRemove) {
  15906. if (this.cameras.length > 0) {
  15907. this.activeCamera = this.cameras[0];
  15908. }
  15909. else {
  15910. this.activeCamera = null;
  15911. }
  15912. }
  15913. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15914. return index;
  15915. };
  15916. Scene.prototype.addLight = function (newLight) {
  15917. newLight.uniqueId = this._uniqueIdCounter++;
  15918. var position = this.lights.push(newLight);
  15919. this.onNewLightAddedObservable.notifyObservers(newLight);
  15920. };
  15921. Scene.prototype.addCamera = function (newCamera) {
  15922. newCamera.uniqueId = this._uniqueIdCounter++;
  15923. var position = this.cameras.push(newCamera);
  15924. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15925. };
  15926. /**
  15927. * Switch active camera
  15928. * @param {Camera} newCamera - new active camera
  15929. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15930. */
  15931. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15932. if (attachControl === void 0) { attachControl = true; }
  15933. var canvas = this._engine.getRenderingCanvas();
  15934. this.activeCamera.detachControl(canvas);
  15935. this.activeCamera = newCamera;
  15936. if (attachControl) {
  15937. newCamera.attachControl(canvas);
  15938. }
  15939. };
  15940. /**
  15941. * sets the active camera of the scene using its ID
  15942. * @param {string} id - the camera's ID
  15943. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15944. * @see activeCamera
  15945. */
  15946. Scene.prototype.setActiveCameraByID = function (id) {
  15947. var camera = this.getCameraByID(id);
  15948. if (camera) {
  15949. this.activeCamera = camera;
  15950. return camera;
  15951. }
  15952. return null;
  15953. };
  15954. /**
  15955. * sets the active camera of the scene using its name
  15956. * @param {string} name - the camera's name
  15957. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15958. * @see activeCamera
  15959. */
  15960. Scene.prototype.setActiveCameraByName = function (name) {
  15961. var camera = this.getCameraByName(name);
  15962. if (camera) {
  15963. this.activeCamera = camera;
  15964. return camera;
  15965. }
  15966. return null;
  15967. };
  15968. /**
  15969. * get a material using its id
  15970. * @param {string} the material's ID
  15971. * @return {BABYLON.Material|null} the material or null if none found.
  15972. */
  15973. Scene.prototype.getMaterialByID = function (id) {
  15974. for (var index = 0; index < this.materials.length; index++) {
  15975. if (this.materials[index].id === id) {
  15976. return this.materials[index];
  15977. }
  15978. }
  15979. return null;
  15980. };
  15981. /**
  15982. * get a material using its name
  15983. * @param {string} the material's name
  15984. * @return {BABYLON.Material|null} the material or null if none found.
  15985. */
  15986. Scene.prototype.getMaterialByName = function (name) {
  15987. for (var index = 0; index < this.materials.length; index++) {
  15988. if (this.materials[index].name === name) {
  15989. return this.materials[index];
  15990. }
  15991. }
  15992. return null;
  15993. };
  15994. Scene.prototype.getLensFlareSystemByName = function (name) {
  15995. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15996. if (this.lensFlareSystems[index].name === name) {
  15997. return this.lensFlareSystems[index];
  15998. }
  15999. }
  16000. return null;
  16001. };
  16002. Scene.prototype.getLensFlareSystemByID = function (id) {
  16003. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16004. if (this.lensFlareSystems[index].id === id) {
  16005. return this.lensFlareSystems[index];
  16006. }
  16007. }
  16008. return null;
  16009. };
  16010. Scene.prototype.getCameraByID = function (id) {
  16011. for (var index = 0; index < this.cameras.length; index++) {
  16012. if (this.cameras[index].id === id) {
  16013. return this.cameras[index];
  16014. }
  16015. }
  16016. return null;
  16017. };
  16018. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16019. for (var index = 0; index < this.cameras.length; index++) {
  16020. if (this.cameras[index].uniqueId === uniqueId) {
  16021. return this.cameras[index];
  16022. }
  16023. }
  16024. return null;
  16025. };
  16026. /**
  16027. * get a camera using its name
  16028. * @param {string} the camera's name
  16029. * @return {BABYLON.Camera|null} the camera or null if none found.
  16030. */
  16031. Scene.prototype.getCameraByName = function (name) {
  16032. for (var index = 0; index < this.cameras.length; index++) {
  16033. if (this.cameras[index].name === name) {
  16034. return this.cameras[index];
  16035. }
  16036. }
  16037. return null;
  16038. };
  16039. /**
  16040. * get a bone using its id
  16041. * @param {string} the bone's id
  16042. * @return {BABYLON.Bone|null} the bone or null if not found
  16043. */
  16044. Scene.prototype.getBoneByID = function (id) {
  16045. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16046. var skeleton = this.skeletons[skeletonIndex];
  16047. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16048. if (skeleton.bones[boneIndex].id === id) {
  16049. return skeleton.bones[boneIndex];
  16050. }
  16051. }
  16052. }
  16053. return null;
  16054. };
  16055. /**
  16056. * get a bone using its id
  16057. * @param {string} the bone's name
  16058. * @return {BABYLON.Bone|null} the bone or null if not found
  16059. */
  16060. Scene.prototype.getBoneByName = function (name) {
  16061. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16062. var skeleton = this.skeletons[skeletonIndex];
  16063. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16064. if (skeleton.bones[boneIndex].name === name) {
  16065. return skeleton.bones[boneIndex];
  16066. }
  16067. }
  16068. }
  16069. return null;
  16070. };
  16071. /**
  16072. * get a light node using its name
  16073. * @param {string} the light's name
  16074. * @return {BABYLON.Light|null} the light or null if none found.
  16075. */
  16076. Scene.prototype.getLightByName = function (name) {
  16077. for (var index = 0; index < this.lights.length; index++) {
  16078. if (this.lights[index].name === name) {
  16079. return this.lights[index];
  16080. }
  16081. }
  16082. return null;
  16083. };
  16084. /**
  16085. * get a light node using its ID
  16086. * @param {string} the light's id
  16087. * @return {BABYLON.Light|null} the light or null if none found.
  16088. */
  16089. Scene.prototype.getLightByID = function (id) {
  16090. for (var index = 0; index < this.lights.length; index++) {
  16091. if (this.lights[index].id === id) {
  16092. return this.lights[index];
  16093. }
  16094. }
  16095. return null;
  16096. };
  16097. /**
  16098. * get a light node using its scene-generated unique ID
  16099. * @param {number} the light's unique id
  16100. * @return {BABYLON.Light|null} the light or null if none found.
  16101. */
  16102. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16103. for (var index = 0; index < this.lights.length; index++) {
  16104. if (this.lights[index].uniqueId === uniqueId) {
  16105. return this.lights[index];
  16106. }
  16107. }
  16108. return null;
  16109. };
  16110. /**
  16111. * get a particle system by id
  16112. * @param id {number} the particle system id
  16113. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16114. */
  16115. Scene.prototype.getParticleSystemByID = function (id) {
  16116. for (var index = 0; index < this.particleSystems.length; index++) {
  16117. if (this.particleSystems[index].id === id) {
  16118. return this.particleSystems[index];
  16119. }
  16120. }
  16121. return null;
  16122. };
  16123. /**
  16124. * get a geometry using its ID
  16125. * @param {string} the geometry's id
  16126. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16127. */
  16128. Scene.prototype.getGeometryByID = function (id) {
  16129. for (var index = 0; index < this._geometries.length; index++) {
  16130. if (this._geometries[index].id === id) {
  16131. return this._geometries[index];
  16132. }
  16133. }
  16134. return null;
  16135. };
  16136. /**
  16137. * add a new geometry to this scene.
  16138. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16139. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16140. * @return {boolean} was the geometry added or not
  16141. */
  16142. Scene.prototype.pushGeometry = function (geometry, force) {
  16143. if (!force && this.getGeometryByID(geometry.id)) {
  16144. return false;
  16145. }
  16146. this._geometries.push(geometry);
  16147. //notify the collision coordinator
  16148. this.collisionCoordinator.onGeometryAdded(geometry);
  16149. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16150. return true;
  16151. };
  16152. /**
  16153. * Removes an existing geometry
  16154. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16155. * @return {boolean} was the geometry removed or not
  16156. */
  16157. Scene.prototype.removeGeometry = function (geometry) {
  16158. var index = this._geometries.indexOf(geometry);
  16159. if (index > -1) {
  16160. this._geometries.splice(index, 1);
  16161. //notify the collision coordinator
  16162. this.collisionCoordinator.onGeometryDeleted(geometry);
  16163. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16164. return true;
  16165. }
  16166. return false;
  16167. };
  16168. Scene.prototype.getGeometries = function () {
  16169. return this._geometries;
  16170. };
  16171. /**
  16172. * Get the first added mesh found of a given ID
  16173. * @param {string} id - the id to search for
  16174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16175. */
  16176. Scene.prototype.getMeshByID = function (id) {
  16177. for (var index = 0; index < this.meshes.length; index++) {
  16178. if (this.meshes[index].id === id) {
  16179. return this.meshes[index];
  16180. }
  16181. }
  16182. return null;
  16183. };
  16184. Scene.prototype.getMeshesByID = function (id) {
  16185. return this.meshes.filter(function (m) {
  16186. return m.id === id;
  16187. });
  16188. };
  16189. /**
  16190. * Get a mesh with its auto-generated unique id
  16191. * @param {number} uniqueId - the unique id to search for
  16192. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16193. */
  16194. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16195. for (var index = 0; index < this.meshes.length; index++) {
  16196. if (this.meshes[index].uniqueId === uniqueId) {
  16197. return this.meshes[index];
  16198. }
  16199. }
  16200. return null;
  16201. };
  16202. /**
  16203. * Get a the last added mesh found of a given ID
  16204. * @param {string} id - the id to search for
  16205. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16206. */
  16207. Scene.prototype.getLastMeshByID = function (id) {
  16208. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16209. if (this.meshes[index].id === id) {
  16210. return this.meshes[index];
  16211. }
  16212. }
  16213. return null;
  16214. };
  16215. /**
  16216. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16217. * @param {string} id - the id to search for
  16218. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16219. */
  16220. Scene.prototype.getLastEntryByID = function (id) {
  16221. var index;
  16222. for (index = this.meshes.length - 1; index >= 0; index--) {
  16223. if (this.meshes[index].id === id) {
  16224. return this.meshes[index];
  16225. }
  16226. }
  16227. for (index = this.cameras.length - 1; index >= 0; index--) {
  16228. if (this.cameras[index].id === id) {
  16229. return this.cameras[index];
  16230. }
  16231. }
  16232. for (index = this.lights.length - 1; index >= 0; index--) {
  16233. if (this.lights[index].id === id) {
  16234. return this.lights[index];
  16235. }
  16236. }
  16237. return null;
  16238. };
  16239. Scene.prototype.getNodeByID = function (id) {
  16240. var mesh = this.getMeshByID(id);
  16241. if (mesh) {
  16242. return mesh;
  16243. }
  16244. var light = this.getLightByID(id);
  16245. if (light) {
  16246. return light;
  16247. }
  16248. var camera = this.getCameraByID(id);
  16249. if (camera) {
  16250. return camera;
  16251. }
  16252. var bone = this.getBoneByID(id);
  16253. return bone;
  16254. };
  16255. Scene.prototype.getNodeByName = function (name) {
  16256. var mesh = this.getMeshByName(name);
  16257. if (mesh) {
  16258. return mesh;
  16259. }
  16260. var light = this.getLightByName(name);
  16261. if (light) {
  16262. return light;
  16263. }
  16264. var camera = this.getCameraByName(name);
  16265. if (camera) {
  16266. return camera;
  16267. }
  16268. var bone = this.getBoneByName(name);
  16269. return bone;
  16270. };
  16271. Scene.prototype.getMeshByName = function (name) {
  16272. for (var index = 0; index < this.meshes.length; index++) {
  16273. if (this.meshes[index].name === name) {
  16274. return this.meshes[index];
  16275. }
  16276. }
  16277. return null;
  16278. };
  16279. Scene.prototype.getSoundByName = function (name) {
  16280. var index;
  16281. if (BABYLON.AudioEngine) {
  16282. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16283. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16284. return this.mainSoundTrack.soundCollection[index];
  16285. }
  16286. }
  16287. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16288. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16289. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16290. return this.soundTracks[sdIndex].soundCollection[index];
  16291. }
  16292. }
  16293. }
  16294. }
  16295. return null;
  16296. };
  16297. Scene.prototype.getLastSkeletonByID = function (id) {
  16298. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16299. if (this.skeletons[index].id === id) {
  16300. return this.skeletons[index];
  16301. }
  16302. }
  16303. return null;
  16304. };
  16305. Scene.prototype.getSkeletonById = function (id) {
  16306. for (var index = 0; index < this.skeletons.length; index++) {
  16307. if (this.skeletons[index].id === id) {
  16308. return this.skeletons[index];
  16309. }
  16310. }
  16311. return null;
  16312. };
  16313. Scene.prototype.getSkeletonByName = function (name) {
  16314. for (var index = 0; index < this.skeletons.length; index++) {
  16315. if (this.skeletons[index].name === name) {
  16316. return this.skeletons[index];
  16317. }
  16318. }
  16319. return null;
  16320. };
  16321. Scene.prototype.isActiveMesh = function (mesh) {
  16322. return (this._activeMeshes.indexOf(mesh) !== -1);
  16323. };
  16324. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16325. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16326. var material = subMesh.getMaterial();
  16327. if (mesh.showSubMeshesBoundingBox) {
  16328. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16329. }
  16330. if (material) {
  16331. // Render targets
  16332. if (material.getRenderTargetTextures) {
  16333. if (this._processedMaterials.indexOf(material) === -1) {
  16334. this._processedMaterials.push(material);
  16335. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16336. }
  16337. }
  16338. // Dispatch
  16339. this._activeIndices.addCount(subMesh.indexCount, false);
  16340. this._renderingManager.dispatch(subMesh);
  16341. }
  16342. }
  16343. };
  16344. Scene.prototype._isInIntermediateRendering = function () {
  16345. return this._intermediateRendering;
  16346. };
  16347. Scene.prototype._evaluateActiveMeshes = function () {
  16348. this.activeCamera._activeMeshes.reset();
  16349. this._activeMeshes.reset();
  16350. this._renderingManager.reset();
  16351. this._processedMaterials.reset();
  16352. this._activeParticleSystems.reset();
  16353. this._activeSkeletons.reset();
  16354. this._softwareSkinnedMeshes.reset();
  16355. this._boundingBoxRenderer.reset();
  16356. this._edgesRenderers.reset();
  16357. // Meshes
  16358. var meshes;
  16359. var len;
  16360. if (this._selectionOctree) {
  16361. var selection = this._selectionOctree.select(this._frustumPlanes);
  16362. meshes = selection.data;
  16363. len = selection.length;
  16364. }
  16365. else {
  16366. len = this.meshes.length;
  16367. meshes = this.meshes;
  16368. }
  16369. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16370. var mesh = meshes[meshIndex];
  16371. if (mesh.isBlocked) {
  16372. continue;
  16373. }
  16374. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16375. if (!mesh.isReady() || !mesh.isEnabled()) {
  16376. continue;
  16377. }
  16378. mesh.computeWorldMatrix();
  16379. // Intersections
  16380. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16381. this._meshesForIntersections.pushNoDuplicate(mesh);
  16382. }
  16383. // Switch to current LOD
  16384. var meshLOD = mesh.getLOD(this.activeCamera);
  16385. if (!meshLOD) {
  16386. continue;
  16387. }
  16388. mesh._preActivate();
  16389. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16390. this._activeMeshes.push(mesh);
  16391. this.activeCamera._activeMeshes.push(mesh);
  16392. mesh._activate(this._renderId);
  16393. this._activeMesh(meshLOD);
  16394. }
  16395. }
  16396. // Particle systems
  16397. this._particlesDuration.beginMonitoring();
  16398. var beforeParticlesDate = BABYLON.Tools.Now;
  16399. if (this.particlesEnabled) {
  16400. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16401. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16402. var particleSystem = this.particleSystems[particleIndex];
  16403. if (!particleSystem.isStarted()) {
  16404. continue;
  16405. }
  16406. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16407. this._activeParticleSystems.push(particleSystem);
  16408. particleSystem.animate();
  16409. }
  16410. }
  16411. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16412. }
  16413. this._particlesDuration.endMonitoring(false);
  16414. };
  16415. Scene.prototype._activeMesh = function (mesh) {
  16416. if (mesh.skeleton && this.skeletonsEnabled) {
  16417. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16418. mesh.skeleton.prepare();
  16419. }
  16420. if (!mesh.computeBonesUsingShaders) {
  16421. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16422. }
  16423. }
  16424. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16425. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  16426. }
  16427. if (mesh._edgesRenderer) {
  16428. this._edgesRenderers.push(mesh._edgesRenderer);
  16429. }
  16430. if (mesh && mesh.subMeshes) {
  16431. // Submeshes Octrees
  16432. var len;
  16433. var subMeshes;
  16434. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16435. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16436. len = intersections.length;
  16437. subMeshes = intersections.data;
  16438. }
  16439. else {
  16440. subMeshes = mesh.subMeshes;
  16441. len = subMeshes.length;
  16442. }
  16443. for (var subIndex = 0; subIndex < len; subIndex++) {
  16444. var subMesh = subMeshes[subIndex];
  16445. this._evaluateSubMesh(subMesh, mesh);
  16446. }
  16447. }
  16448. };
  16449. Scene.prototype.updateTransformMatrix = function (force) {
  16450. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16451. };
  16452. Scene.prototype._renderForCamera = function (camera) {
  16453. var engine = this._engine;
  16454. var startTime = BABYLON.Tools.Now;
  16455. this.activeCamera = camera;
  16456. if (!this.activeCamera)
  16457. throw new Error("Active camera not set");
  16458. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16459. // Viewport
  16460. engine.setViewport(this.activeCamera.viewport);
  16461. // Camera
  16462. this.resetCachedMaterial();
  16463. this._renderId++;
  16464. this.updateTransformMatrix();
  16465. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16466. // Meshes
  16467. this._evaluateActiveMeshesDuration.beginMonitoring();
  16468. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16469. this._evaluateActiveMeshes();
  16470. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16471. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16472. // Software skinning
  16473. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16474. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16475. mesh.applySkeleton(mesh.skeleton);
  16476. }
  16477. // Render targets
  16478. this._renderTargetsDuration.beginMonitoring();
  16479. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16480. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16481. this._intermediateRendering = true;
  16482. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16483. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16484. var renderTarget = this._renderTargets.data[renderIndex];
  16485. if (renderTarget._shouldRender()) {
  16486. this._renderId++;
  16487. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16488. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16489. }
  16490. }
  16491. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16492. this._intermediateRendering = false;
  16493. this._renderId++;
  16494. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16495. }
  16496. this._renderTargetsDuration.endMonitoring(false);
  16497. // Prepare Frame
  16498. this.postProcessManager._prepareFrame();
  16499. this._renderDuration.beginMonitoring();
  16500. // Backgrounds
  16501. var layerIndex;
  16502. var layer;
  16503. if (this.layers.length) {
  16504. engine.setDepthBuffer(false);
  16505. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16506. layer = this.layers[layerIndex];
  16507. if (layer.isBackground) {
  16508. layer.render();
  16509. }
  16510. }
  16511. engine.setDepthBuffer(true);
  16512. }
  16513. // Render
  16514. BABYLON.Tools.StartPerformanceCounter("Main render");
  16515. this._renderingManager.render(null, null, true, true);
  16516. BABYLON.Tools.EndPerformanceCounter("Main render");
  16517. // Bounding boxes
  16518. this._boundingBoxRenderer.render();
  16519. // Edges
  16520. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16521. this._edgesRenderers.data[edgesRendererIndex].render();
  16522. }
  16523. // Lens flares
  16524. if (this.lensFlaresEnabled) {
  16525. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16526. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16527. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16528. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16529. lensFlareSystem.render();
  16530. }
  16531. }
  16532. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16533. }
  16534. // Foregrounds
  16535. if (this.layers.length) {
  16536. engine.setDepthBuffer(false);
  16537. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16538. layer = this.layers[layerIndex];
  16539. if (!layer.isBackground) {
  16540. layer.render();
  16541. }
  16542. }
  16543. engine.setDepthBuffer(true);
  16544. }
  16545. this._renderDuration.endMonitoring(false);
  16546. // Finalize frame
  16547. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16548. // Update camera
  16549. this.activeCamera._updateFromScene();
  16550. // Reset some special arrays
  16551. this._renderTargets.reset();
  16552. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16553. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16554. };
  16555. Scene.prototype._processSubCameras = function (camera) {
  16556. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16557. this._renderForCamera(camera);
  16558. return;
  16559. }
  16560. // rig cameras
  16561. for (var index = 0; index < camera._rigCameras.length; index++) {
  16562. this._renderForCamera(camera._rigCameras[index]);
  16563. }
  16564. this.activeCamera = camera;
  16565. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16566. // Update camera
  16567. this.activeCamera._updateFromScene();
  16568. };
  16569. Scene.prototype._checkIntersections = function () {
  16570. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16571. var sourceMesh = this._meshesForIntersections.data[index];
  16572. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16573. var action = sourceMesh.actionManager.actions[actionIndex];
  16574. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16575. var parameters = action.getTriggerParameter();
  16576. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16577. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16578. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16579. if (areIntersecting && currentIntersectionInProgress === -1) {
  16580. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16581. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16582. sourceMesh._intersectionsInProgress.push(otherMesh);
  16583. }
  16584. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16585. sourceMesh._intersectionsInProgress.push(otherMesh);
  16586. }
  16587. }
  16588. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16589. //They intersected, and now they don't.
  16590. //is this trigger an exit trigger? execute an event.
  16591. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16592. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16593. }
  16594. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16595. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16596. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16597. }
  16598. }
  16599. }
  16600. }
  16601. }
  16602. };
  16603. Scene.prototype.render = function () {
  16604. this._lastFrameDuration.beginMonitoring();
  16605. this._particlesDuration.fetchNewFrame();
  16606. this._spritesDuration.fetchNewFrame();
  16607. this._activeParticles.fetchNewFrame();
  16608. this._renderDuration.fetchNewFrame();
  16609. this._renderTargetsDuration.fetchNewFrame();
  16610. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16611. this._totalVertices.fetchNewFrame();
  16612. this._activeIndices.fetchNewFrame();
  16613. this._activeBones.fetchNewFrame();
  16614. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16615. this._meshesForIntersections.reset();
  16616. this.resetCachedMaterial();
  16617. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16618. // Actions
  16619. if (this.actionManager) {
  16620. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16621. }
  16622. //Simplification Queue
  16623. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16624. this.simplificationQueue.executeNext();
  16625. }
  16626. // Animations
  16627. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16628. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16629. this._animate();
  16630. // Physics
  16631. if (this._physicsEngine) {
  16632. BABYLON.Tools.StartPerformanceCounter("Physics");
  16633. this._physicsEngine._step(deltaTime / 1000.0);
  16634. BABYLON.Tools.EndPerformanceCounter("Physics");
  16635. }
  16636. // Before render
  16637. this.onBeforeRenderObservable.notifyObservers(this);
  16638. // Customs render targets
  16639. this._renderTargetsDuration.beginMonitoring();
  16640. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16641. var engine = this.getEngine();
  16642. var currentActiveCamera = this.activeCamera;
  16643. if (this.renderTargetsEnabled) {
  16644. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16645. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16646. var renderTarget = this.customRenderTargets[customIndex];
  16647. if (renderTarget._shouldRender()) {
  16648. this._renderId++;
  16649. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16650. if (!this.activeCamera)
  16651. throw new Error("Active camera not set");
  16652. // Viewport
  16653. engine.setViewport(this.activeCamera.viewport);
  16654. // Camera
  16655. this.updateTransformMatrix();
  16656. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16657. }
  16658. }
  16659. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16660. this._renderId++;
  16661. }
  16662. if (this.customRenderTargets.length > 0) {
  16663. engine.restoreDefaultFramebuffer();
  16664. }
  16665. this._renderTargetsDuration.endMonitoring();
  16666. this.activeCamera = currentActiveCamera;
  16667. // Procedural textures
  16668. if (this.proceduralTexturesEnabled) {
  16669. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16670. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16671. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16672. if (proceduralTexture._shouldRender()) {
  16673. proceduralTexture.render();
  16674. }
  16675. }
  16676. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16677. }
  16678. // Clear
  16679. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16680. // Shadows
  16681. if (this.shadowsEnabled) {
  16682. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16683. var light = this.lights[lightIndex];
  16684. var shadowGenerator = light.getShadowGenerator();
  16685. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16686. this._renderTargets.push(shadowGenerator.getShadowMap());
  16687. }
  16688. }
  16689. }
  16690. // Depth renderer
  16691. if (this._depthRenderer) {
  16692. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16693. }
  16694. // RenderPipeline
  16695. this.postProcessRenderPipelineManager.update();
  16696. // Multi-cameras?
  16697. if (this.activeCameras.length > 0) {
  16698. var currentRenderId = this._renderId;
  16699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16700. this._renderId = currentRenderId;
  16701. if (cameraIndex > 0) {
  16702. this._engine.clear(0, false, true);
  16703. }
  16704. this._processSubCameras(this.activeCameras[cameraIndex]);
  16705. }
  16706. }
  16707. else {
  16708. if (!this.activeCamera) {
  16709. throw new Error("No camera defined");
  16710. }
  16711. this._processSubCameras(this.activeCamera);
  16712. }
  16713. // Intersection checks
  16714. this._checkIntersections();
  16715. // Update the audio listener attached to the camera
  16716. if (BABYLON.AudioEngine) {
  16717. this._updateAudioParameters();
  16718. }
  16719. // After render
  16720. if (this.afterRender) {
  16721. this.afterRender();
  16722. }
  16723. this.onAfterRenderObservable.notifyObservers(this);
  16724. // Cleaning
  16725. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16726. this._toBeDisposed.data[index].dispose();
  16727. this._toBeDisposed[index] = null;
  16728. }
  16729. this._toBeDisposed.reset();
  16730. if (this.dumpNextRenderTargets) {
  16731. this.dumpNextRenderTargets = false;
  16732. }
  16733. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16734. this._lastFrameDuration.endMonitoring();
  16735. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16736. this._totalLightsCounter.addCount(this.lights.length, true);
  16737. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16738. this._totalTexturesCounter.addCount(this.textures.length, true);
  16739. this._activeBones.addCount(0, true);
  16740. this._activeIndices.addCount(0, true);
  16741. this._activeParticles.addCount(0, true);
  16742. };
  16743. Scene.prototype._updateAudioParameters = function () {
  16744. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16745. return;
  16746. }
  16747. var listeningCamera;
  16748. var audioEngine = BABYLON.Engine.audioEngine;
  16749. if (this.activeCameras.length > 0) {
  16750. listeningCamera = this.activeCameras[0];
  16751. }
  16752. else {
  16753. listeningCamera = this.activeCamera;
  16754. }
  16755. if (listeningCamera && audioEngine.canUseWebAudio) {
  16756. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16757. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16758. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16759. cameraDirection.normalize();
  16760. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16761. var i;
  16762. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16763. var sound = this.mainSoundTrack.soundCollection[i];
  16764. if (sound.useCustomAttenuation) {
  16765. sound.updateDistanceFromListener();
  16766. }
  16767. }
  16768. for (i = 0; i < this.soundTracks.length; i++) {
  16769. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16770. sound = this.soundTracks[i].soundCollection[j];
  16771. if (sound.useCustomAttenuation) {
  16772. sound.updateDistanceFromListener();
  16773. }
  16774. }
  16775. }
  16776. }
  16777. };
  16778. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16779. // Audio
  16780. get: function () {
  16781. return this._audioEnabled;
  16782. },
  16783. set: function (value) {
  16784. this._audioEnabled = value;
  16785. if (BABYLON.AudioEngine) {
  16786. if (this._audioEnabled) {
  16787. this._enableAudio();
  16788. }
  16789. else {
  16790. this._disableAudio();
  16791. }
  16792. }
  16793. },
  16794. enumerable: true,
  16795. configurable: true
  16796. });
  16797. Scene.prototype._disableAudio = function () {
  16798. var i;
  16799. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16800. this.mainSoundTrack.soundCollection[i].pause();
  16801. }
  16802. for (i = 0; i < this.soundTracks.length; i++) {
  16803. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16804. this.soundTracks[i].soundCollection[j].pause();
  16805. }
  16806. }
  16807. };
  16808. Scene.prototype._enableAudio = function () {
  16809. var i;
  16810. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16811. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16812. this.mainSoundTrack.soundCollection[i].play();
  16813. }
  16814. }
  16815. for (i = 0; i < this.soundTracks.length; i++) {
  16816. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16817. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16818. this.soundTracks[i].soundCollection[j].play();
  16819. }
  16820. }
  16821. }
  16822. };
  16823. Object.defineProperty(Scene.prototype, "headphone", {
  16824. get: function () {
  16825. return this._headphone;
  16826. },
  16827. set: function (value) {
  16828. this._headphone = value;
  16829. if (BABYLON.AudioEngine) {
  16830. if (this._headphone) {
  16831. this._switchAudioModeForHeadphones();
  16832. }
  16833. else {
  16834. this._switchAudioModeForNormalSpeakers();
  16835. }
  16836. }
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Scene.prototype._switchAudioModeForHeadphones = function () {
  16842. this.mainSoundTrack.switchPanningModelToHRTF();
  16843. for (var i = 0; i < this.soundTracks.length; i++) {
  16844. this.soundTracks[i].switchPanningModelToHRTF();
  16845. }
  16846. };
  16847. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16848. this.mainSoundTrack.switchPanningModelToEqualPower();
  16849. for (var i = 0; i < this.soundTracks.length; i++) {
  16850. this.soundTracks[i].switchPanningModelToEqualPower();
  16851. }
  16852. };
  16853. Scene.prototype.enableDepthRenderer = function () {
  16854. if (this._depthRenderer) {
  16855. return this._depthRenderer;
  16856. }
  16857. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16858. return this._depthRenderer;
  16859. };
  16860. Scene.prototype.disableDepthRenderer = function () {
  16861. if (!this._depthRenderer) {
  16862. return;
  16863. }
  16864. this._depthRenderer.dispose();
  16865. this._depthRenderer = null;
  16866. };
  16867. Scene.prototype.freezeMaterials = function () {
  16868. for (var i = 0; i < this.materials.length; i++) {
  16869. this.materials[i].freeze();
  16870. }
  16871. };
  16872. Scene.prototype.unfreezeMaterials = function () {
  16873. for (var i = 0; i < this.materials.length; i++) {
  16874. this.materials[i].unfreeze();
  16875. }
  16876. };
  16877. Scene.prototype.dispose = function () {
  16878. this.beforeRender = null;
  16879. this.afterRender = null;
  16880. this.skeletons = [];
  16881. this._boundingBoxRenderer.dispose();
  16882. if (this._depthRenderer) {
  16883. this._depthRenderer.dispose();
  16884. }
  16885. // Debug layer
  16886. if (this._debugLayer) {
  16887. this._debugLayer.hide();
  16888. }
  16889. // Events
  16890. this.onDisposeObservable.notifyObservers(this);
  16891. this.onDisposeObservable.clear();
  16892. this.onBeforeRenderObservable.clear();
  16893. this.onAfterRenderObservable.clear();
  16894. this.detachControl();
  16895. // Release sounds & sounds tracks
  16896. if (BABYLON.AudioEngine) {
  16897. this.disposeSounds();
  16898. }
  16899. // Detach cameras
  16900. var canvas = this._engine.getRenderingCanvas();
  16901. var index;
  16902. for (index = 0; index < this.cameras.length; index++) {
  16903. this.cameras[index].detachControl(canvas);
  16904. }
  16905. // Release lights
  16906. while (this.lights.length) {
  16907. this.lights[0].dispose();
  16908. }
  16909. // Release meshes
  16910. while (this.meshes.length) {
  16911. this.meshes[0].dispose(true);
  16912. }
  16913. // Release cameras
  16914. while (this.cameras.length) {
  16915. this.cameras[0].dispose();
  16916. }
  16917. // Release materials
  16918. while (this.materials.length) {
  16919. this.materials[0].dispose();
  16920. }
  16921. // Release particles
  16922. while (this.particleSystems.length) {
  16923. this.particleSystems[0].dispose();
  16924. }
  16925. // Release sprites
  16926. while (this.spriteManagers.length) {
  16927. this.spriteManagers[0].dispose();
  16928. }
  16929. // Release layers
  16930. while (this.layers.length) {
  16931. this.layers[0].dispose();
  16932. }
  16933. // Release textures
  16934. while (this.textures.length) {
  16935. this.textures[0].dispose();
  16936. }
  16937. // Post-processes
  16938. this.postProcessManager.dispose();
  16939. // Physics
  16940. if (this._physicsEngine) {
  16941. this.disablePhysicsEngine();
  16942. }
  16943. // Remove from engine
  16944. index = this._engine.scenes.indexOf(this);
  16945. if (index > -1) {
  16946. this._engine.scenes.splice(index, 1);
  16947. }
  16948. this._engine.wipeCaches();
  16949. };
  16950. // Release sounds & sounds tracks
  16951. Scene.prototype.disposeSounds = function () {
  16952. this.mainSoundTrack.dispose();
  16953. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16954. this.soundTracks[scIndex].dispose();
  16955. }
  16956. };
  16957. // Octrees
  16958. Scene.prototype.getWorldExtends = function () {
  16959. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16960. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16961. for (var index = 0; index < this.meshes.length; index++) {
  16962. var mesh = this.meshes[index];
  16963. mesh.computeWorldMatrix(true);
  16964. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16965. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16966. BABYLON.Tools.CheckExtends(minBox, min, max);
  16967. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16968. }
  16969. return {
  16970. min: min,
  16971. max: max
  16972. };
  16973. };
  16974. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16975. if (maxCapacity === void 0) { maxCapacity = 64; }
  16976. if (maxDepth === void 0) { maxDepth = 2; }
  16977. if (!this._selectionOctree) {
  16978. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16979. }
  16980. var worldExtends = this.getWorldExtends();
  16981. // Update octree
  16982. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16983. return this._selectionOctree;
  16984. };
  16985. // Picking
  16986. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16987. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16988. var engine = this._engine;
  16989. if (!camera) {
  16990. if (!this.activeCamera)
  16991. throw new Error("Active camera not set");
  16992. camera = this.activeCamera;
  16993. }
  16994. var cameraViewport = camera.viewport;
  16995. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16996. // Moving coordinates to local viewport world
  16997. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16998. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16999. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17000. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17001. };
  17002. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17003. var engine = this._engine;
  17004. if (!camera) {
  17005. if (!this.activeCamera)
  17006. throw new Error("Active camera not set");
  17007. camera = this.activeCamera;
  17008. }
  17009. var cameraViewport = camera.viewport;
  17010. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17011. var identity = BABYLON.Matrix.Identity();
  17012. // Moving coordinates to local viewport world
  17013. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17014. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17015. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17016. };
  17017. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17018. var pickingInfo = null;
  17019. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17020. var mesh = this.meshes[meshIndex];
  17021. if (predicate) {
  17022. if (!predicate(mesh)) {
  17023. continue;
  17024. }
  17025. }
  17026. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17027. continue;
  17028. }
  17029. var world = mesh.getWorldMatrix();
  17030. var ray = rayFunction(world);
  17031. var result = mesh.intersects(ray, fastCheck);
  17032. if (!result || !result.hit)
  17033. continue;
  17034. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17035. continue;
  17036. pickingInfo = result;
  17037. if (fastCheck) {
  17038. break;
  17039. }
  17040. }
  17041. return pickingInfo || new BABYLON.PickingInfo();
  17042. };
  17043. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17044. var pickingInfo = null;
  17045. camera = camera || this.activeCamera;
  17046. if (this.spriteManagers.length > 0) {
  17047. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17048. var spriteManager = this.spriteManagers[spriteIndex];
  17049. if (!spriteManager.isPickable) {
  17050. continue;
  17051. }
  17052. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17053. if (!result || !result.hit)
  17054. continue;
  17055. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17056. continue;
  17057. pickingInfo = result;
  17058. if (fastCheck) {
  17059. break;
  17060. }
  17061. }
  17062. }
  17063. return pickingInfo || new BABYLON.PickingInfo();
  17064. };
  17065. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17066. var _this = this;
  17067. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17068. /// <param name="x">X position on screen</param>
  17069. /// <param name="y">Y position on screen</param>
  17070. /// <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>
  17071. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17072. /// <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>
  17073. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17074. };
  17075. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17076. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17077. /// <param name="x">X position on screen</param>
  17078. /// <param name="y">Y position on screen</param>
  17079. /// <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>
  17080. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17081. /// <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>
  17082. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17083. };
  17084. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17085. var _this = this;
  17086. return this._internalPick(function (world) {
  17087. if (!_this._pickWithRayInverseMatrix) {
  17088. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17089. }
  17090. world.invertToRef(_this._pickWithRayInverseMatrix);
  17091. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17092. }, predicate, fastCheck);
  17093. };
  17094. Scene.prototype.setPointerOverMesh = function (mesh) {
  17095. if (this._pointerOverMesh === mesh) {
  17096. return;
  17097. }
  17098. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17099. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17100. }
  17101. this._pointerOverMesh = mesh;
  17102. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17103. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17104. }
  17105. };
  17106. Scene.prototype.getPointerOverMesh = function () {
  17107. return this._pointerOverMesh;
  17108. };
  17109. Scene.prototype.setPointerOverSprite = function (sprite) {
  17110. if (this._pointerOverSprite === sprite) {
  17111. return;
  17112. }
  17113. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17114. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17115. }
  17116. this._pointerOverSprite = sprite;
  17117. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17118. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17119. }
  17120. };
  17121. Scene.prototype.getPointerOverSprite = function () {
  17122. return this._pointerOverSprite;
  17123. };
  17124. // Physics
  17125. Scene.prototype.getPhysicsEngine = function () {
  17126. return this._physicsEngine;
  17127. };
  17128. /**
  17129. * Enables physics to the current scene
  17130. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17131. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17132. * @return {boolean} was the physics engine initialized
  17133. */
  17134. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17135. if (this._physicsEngine) {
  17136. return true;
  17137. }
  17138. try {
  17139. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17140. return true;
  17141. }
  17142. catch (e) {
  17143. BABYLON.Tools.Error(e.message);
  17144. return false;
  17145. }
  17146. };
  17147. Scene.prototype.disablePhysicsEngine = function () {
  17148. if (!this._physicsEngine) {
  17149. return;
  17150. }
  17151. this._physicsEngine.dispose();
  17152. this._physicsEngine = undefined;
  17153. };
  17154. Scene.prototype.isPhysicsEnabled = function () {
  17155. return this._physicsEngine !== undefined;
  17156. };
  17157. /**
  17158. *
  17159. * Sets the gravity of the physics engine (and NOT of the scene)
  17160. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17161. */
  17162. Scene.prototype.setGravity = function (gravity) {
  17163. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17164. if (!this._physicsEngine) {
  17165. return;
  17166. }
  17167. this._physicsEngine.setGravity(gravity);
  17168. };
  17169. /**
  17170. * Legacy support, using the new API
  17171. * @Deprecated
  17172. */
  17173. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17174. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17175. if (parts.parts) {
  17176. options = parts;
  17177. parts = parts.parts;
  17178. }
  17179. var mainMesh = parts[0].mesh;
  17180. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17181. for (var index = 1; index < parts.length; index++) {
  17182. var mesh = parts[index].mesh;
  17183. if (mesh.parent !== mainMesh) {
  17184. mesh.position = mesh.position.subtract(mainMesh.position);
  17185. mesh.parent = mainMesh;
  17186. }
  17187. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17188. }
  17189. mainMesh.physicsImpostor.forceUpdate();
  17190. };
  17191. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17192. var mesh = compound.parts[0].mesh;
  17193. mesh.physicsImpostor.dispose();
  17194. mesh.physicsImpostor = null;
  17195. };
  17196. // Misc.
  17197. Scene.prototype.createDefaultCameraOrLight = function () {
  17198. // Light
  17199. if (this.lights.length === 0) {
  17200. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17201. }
  17202. // Camera
  17203. if (!this.activeCamera) {
  17204. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17205. // Compute position
  17206. var worldExtends = this.getWorldExtends();
  17207. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17208. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17209. camera.setTarget(worldCenter);
  17210. this.activeCamera = camera;
  17211. }
  17212. };
  17213. // Tags
  17214. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17215. if (tagsQuery === undefined) {
  17216. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17217. return list;
  17218. }
  17219. var listByTags = [];
  17220. forEach = forEach || (function (item) { return; });
  17221. for (var i in list) {
  17222. var item = list[i];
  17223. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17224. listByTags.push(item);
  17225. forEach(item);
  17226. }
  17227. }
  17228. return listByTags;
  17229. };
  17230. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17231. return this._getByTags(this.meshes, tagsQuery, forEach);
  17232. };
  17233. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17234. return this._getByTags(this.cameras, tagsQuery, forEach);
  17235. };
  17236. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17237. return this._getByTags(this.lights, tagsQuery, forEach);
  17238. };
  17239. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17240. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17241. };
  17242. // Statics
  17243. Scene._FOGMODE_NONE = 0;
  17244. Scene._FOGMODE_EXP = 1;
  17245. Scene._FOGMODE_EXP2 = 2;
  17246. Scene._FOGMODE_LINEAR = 3;
  17247. Scene.MinDeltaTime = 1.0;
  17248. Scene.MaxDeltaTime = 1000.0;
  17249. return Scene;
  17250. })();
  17251. BABYLON.Scene = Scene;
  17252. })(BABYLON || (BABYLON = {}));
  17253. var BABYLON;
  17254. (function (BABYLON) {
  17255. var Buffer = (function () {
  17256. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17257. if (engine instanceof BABYLON.Mesh) {
  17258. this._engine = engine.getScene().getEngine();
  17259. }
  17260. else {
  17261. this._engine = engine;
  17262. }
  17263. this._updatable = updatable;
  17264. this._data = data;
  17265. this._strideSize = stride;
  17266. if (!postponeInternalCreation) {
  17267. this.create();
  17268. }
  17269. this._instanced = instanced;
  17270. }
  17271. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17272. // a lot of these parameters are ignored as they are overriden by the buffer
  17273. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17274. };
  17275. // Properties
  17276. Buffer.prototype.isUpdatable = function () {
  17277. return this._updatable;
  17278. };
  17279. Buffer.prototype.getData = function () {
  17280. return this._data;
  17281. };
  17282. Buffer.prototype.getBuffer = function () {
  17283. return this._buffer;
  17284. };
  17285. Buffer.prototype.getStrideSize = function () {
  17286. return this._strideSize;
  17287. };
  17288. Buffer.prototype.getIsInstanced = function () {
  17289. return this._instanced;
  17290. };
  17291. // Methods
  17292. Buffer.prototype.create = function (data) {
  17293. if (!data && this._buffer) {
  17294. return; // nothing to do
  17295. }
  17296. data = data || this._data;
  17297. if (!this._buffer) {
  17298. if (this._updatable) {
  17299. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17300. this._data = data;
  17301. }
  17302. else {
  17303. this._buffer = this._engine.createVertexBuffer(data);
  17304. }
  17305. }
  17306. else if (this._updatable) {
  17307. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17308. this._data = data;
  17309. }
  17310. };
  17311. Buffer.prototype.update = function (data) {
  17312. this.create(data);
  17313. };
  17314. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17315. if (!this._buffer) {
  17316. return;
  17317. }
  17318. if (this._updatable) {
  17319. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17320. this._data = null;
  17321. }
  17322. };
  17323. Buffer.prototype.dispose = function () {
  17324. if (!this._buffer) {
  17325. return;
  17326. }
  17327. if (this._engine._releaseBuffer(this._buffer)) {
  17328. this._buffer = null;
  17329. }
  17330. };
  17331. return Buffer;
  17332. })();
  17333. BABYLON.Buffer = Buffer;
  17334. })(BABYLON || (BABYLON = {}));
  17335. var BABYLON;
  17336. (function (BABYLON) {
  17337. var VertexBuffer = (function () {
  17338. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17339. if (!stride) {
  17340. // Deduce stride from kind
  17341. switch (kind) {
  17342. case VertexBuffer.PositionKind:
  17343. stride = 3;
  17344. break;
  17345. case VertexBuffer.NormalKind:
  17346. stride = 3;
  17347. break;
  17348. case VertexBuffer.UVKind:
  17349. case VertexBuffer.UV2Kind:
  17350. case VertexBuffer.UV3Kind:
  17351. case VertexBuffer.UV4Kind:
  17352. case VertexBuffer.UV5Kind:
  17353. case VertexBuffer.UV6Kind:
  17354. stride = 2;
  17355. break;
  17356. case VertexBuffer.ColorKind:
  17357. stride = 4;
  17358. break;
  17359. case VertexBuffer.MatricesIndicesKind:
  17360. case VertexBuffer.MatricesIndicesExtraKind:
  17361. stride = 4;
  17362. break;
  17363. case VertexBuffer.MatricesWeightsKind:
  17364. case VertexBuffer.MatricesWeightsExtraKind:
  17365. stride = 4;
  17366. break;
  17367. }
  17368. }
  17369. if (data instanceof BABYLON.Buffer) {
  17370. if (!stride) {
  17371. stride = data.getStrideSize();
  17372. }
  17373. this._buffer = data;
  17374. this._ownsBuffer = false;
  17375. }
  17376. else {
  17377. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17378. this._ownsBuffer = true;
  17379. }
  17380. this._stride = stride;
  17381. this._offset = offset ? offset : 0;
  17382. this._size = size ? size : stride;
  17383. this._kind = kind;
  17384. }
  17385. VertexBuffer.prototype.getKind = function () {
  17386. return this._kind;
  17387. };
  17388. // Properties
  17389. VertexBuffer.prototype.isUpdatable = function () {
  17390. return this._buffer.isUpdatable();
  17391. };
  17392. VertexBuffer.prototype.getData = function () {
  17393. return this._buffer.getData();
  17394. };
  17395. VertexBuffer.prototype.getBuffer = function () {
  17396. return this._buffer.getBuffer();
  17397. };
  17398. VertexBuffer.prototype.getStrideSize = function () {
  17399. return this._stride;
  17400. };
  17401. VertexBuffer.prototype.getOffset = function () {
  17402. return this._offset;
  17403. };
  17404. VertexBuffer.prototype.getSize = function () {
  17405. return this._size;
  17406. };
  17407. VertexBuffer.prototype.getIsInstanced = function () {
  17408. return this._buffer.getIsInstanced();
  17409. };
  17410. // Methods
  17411. VertexBuffer.prototype.create = function (data) {
  17412. return this._buffer.create(data);
  17413. };
  17414. VertexBuffer.prototype.update = function (data) {
  17415. return this._buffer.update(data);
  17416. };
  17417. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17418. return this._buffer.updateDirectly(data, offset);
  17419. };
  17420. VertexBuffer.prototype.dispose = function () {
  17421. if (this._ownsBuffer) {
  17422. this._buffer.dispose();
  17423. }
  17424. };
  17425. Object.defineProperty(VertexBuffer, "PositionKind", {
  17426. get: function () {
  17427. return VertexBuffer._PositionKind;
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Object.defineProperty(VertexBuffer, "NormalKind", {
  17433. get: function () {
  17434. return VertexBuffer._NormalKind;
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(VertexBuffer, "UVKind", {
  17440. get: function () {
  17441. return VertexBuffer._UVKind;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17447. get: function () {
  17448. return VertexBuffer._UV2Kind;
  17449. },
  17450. enumerable: true,
  17451. configurable: true
  17452. });
  17453. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17454. get: function () {
  17455. return VertexBuffer._UV3Kind;
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17461. get: function () {
  17462. return VertexBuffer._UV4Kind;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17468. get: function () {
  17469. return VertexBuffer._UV5Kind;
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17475. get: function () {
  17476. return VertexBuffer._UV6Kind;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(VertexBuffer, "ColorKind", {
  17482. get: function () {
  17483. return VertexBuffer._ColorKind;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17489. get: function () {
  17490. return VertexBuffer._MatricesIndicesKind;
  17491. },
  17492. enumerable: true,
  17493. configurable: true
  17494. });
  17495. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17496. get: function () {
  17497. return VertexBuffer._MatricesWeightsKind;
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17503. get: function () {
  17504. return VertexBuffer._MatricesIndicesExtraKind;
  17505. },
  17506. enumerable: true,
  17507. configurable: true
  17508. });
  17509. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17510. get: function () {
  17511. return VertexBuffer._MatricesWeightsExtraKind;
  17512. },
  17513. enumerable: true,
  17514. configurable: true
  17515. });
  17516. // Enums
  17517. VertexBuffer._PositionKind = "position";
  17518. VertexBuffer._NormalKind = "normal";
  17519. VertexBuffer._UVKind = "uv";
  17520. VertexBuffer._UV2Kind = "uv2";
  17521. VertexBuffer._UV3Kind = "uv3";
  17522. VertexBuffer._UV4Kind = "uv4";
  17523. VertexBuffer._UV5Kind = "uv5";
  17524. VertexBuffer._UV6Kind = "uv6";
  17525. VertexBuffer._ColorKind = "color";
  17526. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17527. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17528. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17529. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17530. return VertexBuffer;
  17531. })();
  17532. BABYLON.VertexBuffer = VertexBuffer;
  17533. })(BABYLON || (BABYLON = {}));
  17534. var BABYLON;
  17535. (function (BABYLON) {
  17536. /**
  17537. * Creates an instance based on a source mesh.
  17538. */
  17539. var InstancedMesh = (function (_super) {
  17540. __extends(InstancedMesh, _super);
  17541. function InstancedMesh(name, source) {
  17542. _super.call(this, name, source.getScene());
  17543. source.instances.push(this);
  17544. this._sourceMesh = source;
  17545. this.position.copyFrom(source.position);
  17546. this.rotation.copyFrom(source.rotation);
  17547. this.scaling.copyFrom(source.scaling);
  17548. if (source.rotationQuaternion) {
  17549. this.rotationQuaternion = source.rotationQuaternion.clone();
  17550. }
  17551. this.infiniteDistance = source.infiniteDistance;
  17552. this.setPivotMatrix(source.getPivotMatrix());
  17553. this.refreshBoundingInfo();
  17554. this._syncSubMeshes();
  17555. }
  17556. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17557. // Methods
  17558. get: function () {
  17559. return this._sourceMesh.receiveShadows;
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. Object.defineProperty(InstancedMesh.prototype, "material", {
  17565. get: function () {
  17566. return this._sourceMesh.material;
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17572. get: function () {
  17573. return this._sourceMesh.visibility;
  17574. },
  17575. enumerable: true,
  17576. configurable: true
  17577. });
  17578. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17579. get: function () {
  17580. return this._sourceMesh.skeleton;
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17586. get: function () {
  17587. return this._sourceMesh.renderingGroupId;
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. InstancedMesh.prototype.getTotalVertices = function () {
  17593. return this._sourceMesh.getTotalVertices();
  17594. };
  17595. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17596. get: function () {
  17597. return this._sourceMesh;
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17603. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17604. };
  17605. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17606. return this._sourceMesh.isVerticesDataPresent(kind);
  17607. };
  17608. InstancedMesh.prototype.getIndices = function () {
  17609. return this._sourceMesh.getIndices();
  17610. };
  17611. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17612. get: function () {
  17613. return this._sourceMesh._positions;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17619. var meshBB = this._sourceMesh.getBoundingInfo();
  17620. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17621. this._updateBoundingInfo();
  17622. };
  17623. InstancedMesh.prototype._preActivate = function () {
  17624. if (this._currentLOD) {
  17625. this._currentLOD._preActivate();
  17626. }
  17627. };
  17628. InstancedMesh.prototype._activate = function (renderId) {
  17629. if (this._currentLOD) {
  17630. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17631. }
  17632. };
  17633. InstancedMesh.prototype.getLOD = function (camera) {
  17634. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17635. if (this._currentLOD === this.sourceMesh) {
  17636. return this;
  17637. }
  17638. return this._currentLOD;
  17639. };
  17640. InstancedMesh.prototype._syncSubMeshes = function () {
  17641. this.releaseSubMeshes();
  17642. if (this._sourceMesh.subMeshes) {
  17643. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17644. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17645. }
  17646. }
  17647. };
  17648. InstancedMesh.prototype._generatePointsArray = function () {
  17649. return this._sourceMesh._generatePointsArray();
  17650. };
  17651. // Clone
  17652. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17653. var result = this._sourceMesh.createInstance(name);
  17654. // Deep copy
  17655. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17656. // Bounding info
  17657. this.refreshBoundingInfo();
  17658. // Parent
  17659. if (newParent) {
  17660. result.parent = newParent;
  17661. }
  17662. if (!doNotCloneChildren) {
  17663. // Children
  17664. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17665. var mesh = this.getScene().meshes[index];
  17666. if (mesh.parent === this) {
  17667. mesh.clone(mesh.name, result);
  17668. }
  17669. }
  17670. }
  17671. result.computeWorldMatrix(true);
  17672. return result;
  17673. };
  17674. // Dispoe
  17675. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17676. // Remove from mesh
  17677. var index = this._sourceMesh.instances.indexOf(this);
  17678. this._sourceMesh.instances.splice(index, 1);
  17679. _super.prototype.dispose.call(this, doNotRecurse);
  17680. };
  17681. return InstancedMesh;
  17682. })(BABYLON.AbstractMesh);
  17683. BABYLON.InstancedMesh = InstancedMesh;
  17684. })(BABYLON || (BABYLON = {}));
  17685. var BABYLON;
  17686. (function (BABYLON) {
  17687. var _InstancesBatch = (function () {
  17688. function _InstancesBatch() {
  17689. this.mustReturn = false;
  17690. this.visibleInstances = new Array();
  17691. this.renderSelf = new Array();
  17692. }
  17693. return _InstancesBatch;
  17694. })();
  17695. BABYLON._InstancesBatch = _InstancesBatch;
  17696. var Mesh = (function (_super) {
  17697. __extends(Mesh, _super);
  17698. /**
  17699. * @constructor
  17700. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17701. * @param {Scene} scene The scene to add this mesh to.
  17702. * @param {Node} parent The parent of this mesh, if it has one
  17703. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17704. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17705. * When false, achieved by calling a clone(), also passing False.
  17706. * This will make creation of children, recursive.
  17707. */
  17708. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17709. if (parent === void 0) { parent = null; }
  17710. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17711. _super.call(this, name, scene);
  17712. // Events
  17713. /**
  17714. * An event triggered before rendering the mesh
  17715. * @type {BABYLON.Observable}
  17716. */
  17717. this.onBeforeRenderObservable = new BABYLON.Observable();
  17718. /**
  17719. * An event triggered after rendering the mesh
  17720. * @type {BABYLON.Observable}
  17721. */
  17722. this.onAfterRenderObservable = new BABYLON.Observable();
  17723. /**
  17724. * An event triggered before drawing the mesh
  17725. * @type {BABYLON.Observable}
  17726. */
  17727. this.onBeforeDrawObservable = new BABYLON.Observable();
  17728. // Members
  17729. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17730. this.instances = new Array();
  17731. this._LODLevels = new Array();
  17732. this._visibleInstances = {};
  17733. this._renderIdForInstances = new Array();
  17734. this._batchCache = new _InstancesBatch();
  17735. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17736. this._sideOrientation = Mesh._DEFAULTSIDE;
  17737. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17738. if (source) {
  17739. // Geometry
  17740. if (source._geometry) {
  17741. source._geometry.applyToMesh(this);
  17742. }
  17743. // Deep copy
  17744. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17745. // Pivot
  17746. this.setPivotMatrix(source.getPivotMatrix());
  17747. this.id = name + "." + source.id;
  17748. // Material
  17749. this.material = source.material;
  17750. var index;
  17751. if (!doNotCloneChildren) {
  17752. // Children
  17753. for (index = 0; index < scene.meshes.length; index++) {
  17754. var mesh = scene.meshes[index];
  17755. if (mesh.parent === source) {
  17756. // doNotCloneChildren is always going to be False
  17757. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17758. }
  17759. }
  17760. }
  17761. // Physics clone
  17762. var physicsEngine = this.getScene().getPhysicsEngine();
  17763. if (clonePhysicsImpostor && physicsEngine) {
  17764. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17765. if (impostor) {
  17766. this.physicsImpostor = impostor.clone(this);
  17767. }
  17768. }
  17769. // Particles
  17770. for (index = 0; index < scene.particleSystems.length; index++) {
  17771. var system = scene.particleSystems[index];
  17772. if (system.emitter === source) {
  17773. system.clone(system.name, this);
  17774. }
  17775. }
  17776. this.computeWorldMatrix(true);
  17777. }
  17778. // Parent
  17779. if (parent !== null) {
  17780. this.parent = parent;
  17781. }
  17782. }
  17783. Object.defineProperty(Mesh, "FRONTSIDE", {
  17784. /**
  17785. * Mesh side orientation : usually the external or front surface
  17786. */
  17787. get: function () {
  17788. return Mesh._FRONTSIDE;
  17789. },
  17790. enumerable: true,
  17791. configurable: true
  17792. });
  17793. Object.defineProperty(Mesh, "BACKSIDE", {
  17794. /**
  17795. * Mesh side orientation : usually the internal or back surface
  17796. */
  17797. get: function () {
  17798. return Mesh._BACKSIDE;
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17804. /**
  17805. * Mesh side orientation : both internal and external or front and back surfaces
  17806. */
  17807. get: function () {
  17808. return Mesh._DOUBLESIDE;
  17809. },
  17810. enumerable: true,
  17811. configurable: true
  17812. });
  17813. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17814. /**
  17815. * Mesh side orientation : by default, `FRONTSIDE`
  17816. */
  17817. get: function () {
  17818. return Mesh._DEFAULTSIDE;
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. Object.defineProperty(Mesh, "NO_CAP", {
  17824. /**
  17825. * Mesh cap setting : no cap
  17826. */
  17827. get: function () {
  17828. return Mesh._NO_CAP;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Object.defineProperty(Mesh, "CAP_START", {
  17834. /**
  17835. * Mesh cap setting : one cap at the beginning of the mesh
  17836. */
  17837. get: function () {
  17838. return Mesh._CAP_START;
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. Object.defineProperty(Mesh, "CAP_END", {
  17844. /**
  17845. * Mesh cap setting : one cap at the end of the mesh
  17846. */
  17847. get: function () {
  17848. return Mesh._CAP_END;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(Mesh, "CAP_ALL", {
  17854. /**
  17855. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17856. */
  17857. get: function () {
  17858. return Mesh._CAP_ALL;
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17864. set: function (callback) {
  17865. if (this._onBeforeDrawObserver) {
  17866. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17867. }
  17868. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17869. },
  17870. enumerable: true,
  17871. configurable: true
  17872. });
  17873. // Methods
  17874. /**
  17875. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17876. */
  17877. Mesh.prototype.toString = function (fullDetails) {
  17878. var ret = _super.prototype.toString.call(this, fullDetails);
  17879. ret += ", n vertices: " + this.getTotalVertices();
  17880. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17881. if (this.animations) {
  17882. for (var i = 0; i < this.animations.length; i++) {
  17883. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17884. }
  17885. }
  17886. if (fullDetails) {
  17887. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17888. }
  17889. return ret;
  17890. };
  17891. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17892. get: function () {
  17893. return this._LODLevels.length > 0;
  17894. },
  17895. enumerable: true,
  17896. configurable: true
  17897. });
  17898. Mesh.prototype._sortLODLevels = function () {
  17899. this._LODLevels.sort(function (a, b) {
  17900. if (a.distance < b.distance) {
  17901. return 1;
  17902. }
  17903. if (a.distance > b.distance) {
  17904. return -1;
  17905. }
  17906. return 0;
  17907. });
  17908. };
  17909. /**
  17910. * Add a mesh as LOD level triggered at the given distance.
  17911. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17912. * @param {number} distance The distance from the center of the object to show this level
  17913. * @param {Mesh} mesh The mesh to be added as LOD level
  17914. * @return {Mesh} This mesh (for chaining)
  17915. */
  17916. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17917. if (mesh && mesh._masterMesh) {
  17918. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17919. return this;
  17920. }
  17921. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17922. this._LODLevels.push(level);
  17923. if (mesh) {
  17924. mesh._masterMesh = this;
  17925. }
  17926. this._sortLODLevels();
  17927. return this;
  17928. };
  17929. /**
  17930. * Returns the LOD level mesh at the passed distance or null if not found.
  17931. * It is related to the method `addLODLevel(distance, mesh)`.
  17932. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17933. */
  17934. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17935. for (var index = 0; index < this._LODLevels.length; index++) {
  17936. var level = this._LODLevels[index];
  17937. if (level.distance === distance) {
  17938. return level.mesh;
  17939. }
  17940. }
  17941. return null;
  17942. };
  17943. /**
  17944. * Remove a mesh from the LOD array
  17945. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17946. * @param {Mesh} mesh The mesh to be removed.
  17947. * @return {Mesh} This mesh (for chaining)
  17948. */
  17949. Mesh.prototype.removeLODLevel = function (mesh) {
  17950. for (var index = 0; index < this._LODLevels.length; index++) {
  17951. if (this._LODLevels[index].mesh === mesh) {
  17952. this._LODLevels.splice(index, 1);
  17953. if (mesh) {
  17954. mesh._masterMesh = null;
  17955. }
  17956. }
  17957. }
  17958. this._sortLODLevels();
  17959. return this;
  17960. };
  17961. /**
  17962. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17963. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17964. */
  17965. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17966. if (!this._LODLevels || this._LODLevels.length === 0) {
  17967. return this;
  17968. }
  17969. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17970. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17971. if (this.onLODLevelSelection) {
  17972. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17973. }
  17974. return this;
  17975. }
  17976. for (var index = 0; index < this._LODLevels.length; index++) {
  17977. var level = this._LODLevels[index];
  17978. if (level.distance < distanceToCamera) {
  17979. if (level.mesh) {
  17980. level.mesh._preActivate();
  17981. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17982. }
  17983. if (this.onLODLevelSelection) {
  17984. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17985. }
  17986. return level.mesh;
  17987. }
  17988. }
  17989. if (this.onLODLevelSelection) {
  17990. this.onLODLevelSelection(distanceToCamera, this, this);
  17991. }
  17992. return this;
  17993. };
  17994. Object.defineProperty(Mesh.prototype, "geometry", {
  17995. /**
  17996. * Returns the mesh internal Geometry object.
  17997. */
  17998. get: function () {
  17999. return this._geometry;
  18000. },
  18001. enumerable: true,
  18002. configurable: true
  18003. });
  18004. /**
  18005. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18006. */
  18007. Mesh.prototype.getTotalVertices = function () {
  18008. if (!this._geometry) {
  18009. return 0;
  18010. }
  18011. return this._geometry.getTotalVertices();
  18012. };
  18013. /**
  18014. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18015. * 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.
  18016. * Returns null if the mesh has no geometry or no vertex buffer.
  18017. * Possible `kind` values :
  18018. * - BABYLON.VertexBuffer.PositionKind
  18019. * - BABYLON.VertexBuffer.UVKind
  18020. * - BABYLON.VertexBuffer.UV2Kind
  18021. * - BABYLON.VertexBuffer.UV3Kind
  18022. * - BABYLON.VertexBuffer.UV4Kind
  18023. * - BABYLON.VertexBuffer.UV5Kind
  18024. * - BABYLON.VertexBuffer.UV6Kind
  18025. * - BABYLON.VertexBuffer.ColorKind
  18026. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18027. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18028. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18029. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18030. */
  18031. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18032. if (!this._geometry) {
  18033. return null;
  18034. }
  18035. return this._geometry.getVerticesData(kind, copyWhenShared);
  18036. };
  18037. /**
  18038. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18039. * Returns `undefined` if the mesh has no geometry.
  18040. * Possible `kind` values :
  18041. * - BABYLON.VertexBuffer.PositionKind
  18042. * - BABYLON.VertexBuffer.UVKind
  18043. * - BABYLON.VertexBuffer.UV2Kind
  18044. * - BABYLON.VertexBuffer.UV3Kind
  18045. * - BABYLON.VertexBuffer.UV4Kind
  18046. * - BABYLON.VertexBuffer.UV5Kind
  18047. * - BABYLON.VertexBuffer.UV6Kind
  18048. * - BABYLON.VertexBuffer.ColorKind
  18049. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18050. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18051. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18052. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18053. */
  18054. Mesh.prototype.getVertexBuffer = function (kind) {
  18055. if (!this._geometry) {
  18056. return undefined;
  18057. }
  18058. return this._geometry.getVertexBuffer(kind);
  18059. };
  18060. /**
  18061. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18062. * Possible `kind` values :
  18063. * - BABYLON.VertexBuffer.PositionKind
  18064. * - BABYLON.VertexBuffer.UVKind
  18065. * - BABYLON.VertexBuffer.UV2Kind
  18066. * - BABYLON.VertexBuffer.UV3Kind
  18067. * - BABYLON.VertexBuffer.UV4Kind
  18068. * - BABYLON.VertexBuffer.UV5Kind
  18069. * - BABYLON.VertexBuffer.UV6Kind
  18070. * - BABYLON.VertexBuffer.ColorKind
  18071. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18072. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18073. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18074. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18075. */
  18076. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18077. if (!this._geometry) {
  18078. if (this._delayInfo) {
  18079. return this._delayInfo.indexOf(kind) !== -1;
  18080. }
  18081. return false;
  18082. }
  18083. return this._geometry.isVerticesDataPresent(kind);
  18084. };
  18085. /**
  18086. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18087. * Possible `kind` values :
  18088. * - BABYLON.VertexBuffer.PositionKind
  18089. * - BABYLON.VertexBuffer.UVKind
  18090. * - BABYLON.VertexBuffer.UV2Kind
  18091. * - BABYLON.VertexBuffer.UV3Kind
  18092. * - BABYLON.VertexBuffer.UV4Kind
  18093. * - BABYLON.VertexBuffer.UV5Kind
  18094. * - BABYLON.VertexBuffer.UV6Kind
  18095. * - BABYLON.VertexBuffer.ColorKind
  18096. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18097. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18098. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18099. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18100. */
  18101. Mesh.prototype.getVerticesDataKinds = function () {
  18102. if (!this._geometry) {
  18103. var result = [];
  18104. if (this._delayInfo) {
  18105. for (var kind in this._delayInfo) {
  18106. result.push(kind);
  18107. }
  18108. }
  18109. return result;
  18110. }
  18111. return this._geometry.getVerticesDataKinds();
  18112. };
  18113. /**
  18114. * Returns a positive integer : the total number of indices in this mesh geometry.
  18115. * Returns zero if the mesh has no geometry.
  18116. */
  18117. Mesh.prototype.getTotalIndices = function () {
  18118. if (!this._geometry) {
  18119. return 0;
  18120. }
  18121. return this._geometry.getTotalIndices();
  18122. };
  18123. /**
  18124. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18125. * 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.
  18126. * Returns an empty array if the mesh has no geometry.
  18127. */
  18128. Mesh.prototype.getIndices = function (copyWhenShared) {
  18129. if (!this._geometry) {
  18130. return [];
  18131. }
  18132. return this._geometry.getIndices(copyWhenShared);
  18133. };
  18134. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18135. get: function () {
  18136. return this._masterMesh !== null && this._masterMesh !== undefined;
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. /**
  18142. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18143. */
  18144. Mesh.prototype.isReady = function () {
  18145. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18146. return false;
  18147. }
  18148. return _super.prototype.isReady.call(this);
  18149. };
  18150. /**
  18151. * Boolean : true if the mesh has been disposed.
  18152. */
  18153. Mesh.prototype.isDisposed = function () {
  18154. return this._isDisposed;
  18155. };
  18156. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18157. get: function () {
  18158. return this._sideOrientation;
  18159. },
  18160. /**
  18161. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18162. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18163. */
  18164. set: function (sideO) {
  18165. this._sideOrientation = sideO;
  18166. },
  18167. enumerable: true,
  18168. configurable: true
  18169. });
  18170. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18171. /**
  18172. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18173. * This property is pertinent only for updatable parametric shapes.
  18174. */
  18175. get: function () {
  18176. return this._areNormalsFrozen;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. /**
  18182. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18183. * It has no effect at all on other shapes.
  18184. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18185. */
  18186. Mesh.prototype.freezeNormals = function () {
  18187. this._areNormalsFrozen = true;
  18188. };
  18189. /**
  18190. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18191. * It has no effect at all on other shapes.
  18192. * It reactivates the mesh normals computation if it was previously frozen.
  18193. */
  18194. Mesh.prototype.unfreezeNormals = function () {
  18195. this._areNormalsFrozen = false;
  18196. };
  18197. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18198. /**
  18199. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18200. */
  18201. set: function (count) {
  18202. this._overridenInstanceCount = count;
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. // Methods
  18208. Mesh.prototype._preActivate = function () {
  18209. var sceneRenderId = this.getScene().getRenderId();
  18210. if (this._preActivateId === sceneRenderId) {
  18211. return;
  18212. }
  18213. this._preActivateId = sceneRenderId;
  18214. this._visibleInstances = null;
  18215. };
  18216. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18217. if (this._visibleInstances) {
  18218. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18219. }
  18220. };
  18221. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18222. if (!this._visibleInstances) {
  18223. this._visibleInstances = {};
  18224. this._visibleInstances.defaultRenderId = renderId;
  18225. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18226. }
  18227. if (!this._visibleInstances[renderId]) {
  18228. this._visibleInstances[renderId] = new Array();
  18229. }
  18230. this._visibleInstances[renderId].push(instance);
  18231. };
  18232. /**
  18233. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18234. * This means the mesh underlying bounding box and sphere are recomputed.
  18235. */
  18236. Mesh.prototype.refreshBoundingInfo = function () {
  18237. if (this._boundingInfo.isLocked) {
  18238. return;
  18239. }
  18240. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18241. if (data) {
  18242. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18243. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18244. }
  18245. if (this.subMeshes) {
  18246. for (var index = 0; index < this.subMeshes.length; index++) {
  18247. this.subMeshes[index].refreshBoundingInfo();
  18248. }
  18249. }
  18250. this._updateBoundingInfo();
  18251. };
  18252. Mesh.prototype._createGlobalSubMesh = function () {
  18253. var totalVertices = this.getTotalVertices();
  18254. if (!totalVertices || !this.getIndices()) {
  18255. return null;
  18256. }
  18257. this.releaseSubMeshes();
  18258. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18259. };
  18260. Mesh.prototype.subdivide = function (count) {
  18261. if (count < 1) {
  18262. return;
  18263. }
  18264. var totalIndices = this.getTotalIndices();
  18265. var subdivisionSize = (totalIndices / count) | 0;
  18266. var offset = 0;
  18267. // Ensure that subdivisionSize is a multiple of 3
  18268. while (subdivisionSize % 3 !== 0) {
  18269. subdivisionSize++;
  18270. }
  18271. this.releaseSubMeshes();
  18272. for (var index = 0; index < count; index++) {
  18273. if (offset >= totalIndices) {
  18274. break;
  18275. }
  18276. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18277. offset += subdivisionSize;
  18278. }
  18279. this.synchronizeInstances();
  18280. };
  18281. /**
  18282. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18283. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18284. * The `data` are either a numeric array either a Float32Array.
  18285. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18286. * 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).
  18287. * Note that a new underlying VertexBuffer object is created each call.
  18288. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18289. *
  18290. * Possible `kind` values :
  18291. * - BABYLON.VertexBuffer.PositionKind
  18292. * - BABYLON.VertexBuffer.UVKind
  18293. * - BABYLON.VertexBuffer.UV2Kind
  18294. * - BABYLON.VertexBuffer.UV3Kind
  18295. * - BABYLON.VertexBuffer.UV4Kind
  18296. * - BABYLON.VertexBuffer.UV5Kind
  18297. * - BABYLON.VertexBuffer.UV6Kind
  18298. * - BABYLON.VertexBuffer.ColorKind
  18299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18303. */
  18304. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18305. if (!this._geometry) {
  18306. var vertexData = new BABYLON.VertexData();
  18307. vertexData.set(data, kind);
  18308. var scene = this.getScene();
  18309. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18310. }
  18311. else {
  18312. this._geometry.setVerticesData(kind, data, updatable, stride);
  18313. }
  18314. };
  18315. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18316. if (!this._geometry) {
  18317. var scene = this.getScene();
  18318. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18319. }
  18320. this._geometry.setVerticesBuffer(buffer);
  18321. };
  18322. /**
  18323. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18324. * If the mesh has no geometry, it is simply returned as it is.
  18325. * The `data` are either a numeric array either a Float32Array.
  18326. * No new underlying VertexBuffer object is created.
  18327. * 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.
  18328. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18329. *
  18330. * Possible `kind` values :
  18331. * - BABYLON.VertexBuffer.PositionKind
  18332. * - BABYLON.VertexBuffer.UVKind
  18333. * - BABYLON.VertexBuffer.UV2Kind
  18334. * - BABYLON.VertexBuffer.UV3Kind
  18335. * - BABYLON.VertexBuffer.UV4Kind
  18336. * - BABYLON.VertexBuffer.UV5Kind
  18337. * - BABYLON.VertexBuffer.UV6Kind
  18338. * - BABYLON.VertexBuffer.ColorKind
  18339. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18340. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18341. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18342. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18343. */
  18344. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18345. if (!this._geometry) {
  18346. return;
  18347. }
  18348. if (!makeItUnique) {
  18349. this._geometry.updateVerticesData(kind, data, updateExtends);
  18350. }
  18351. else {
  18352. this.makeGeometryUnique();
  18353. this.updateVerticesData(kind, data, updateExtends, false);
  18354. }
  18355. };
  18356. /**
  18357. * Deprecated since BabylonJS v2.3
  18358. */
  18359. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18360. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18361. if (!this._geometry) {
  18362. return;
  18363. }
  18364. if (!makeItUnique) {
  18365. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18366. }
  18367. else {
  18368. this.makeGeometryUnique();
  18369. this.updateVerticesDataDirectly(kind, data, offset, false);
  18370. }
  18371. };
  18372. /**
  18373. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18374. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18375. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18376. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18377. */
  18378. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18379. if (computeNormals === void 0) { computeNormals = true; }
  18380. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18381. positionFunction(positions);
  18382. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18383. if (computeNormals) {
  18384. var indices = this.getIndices();
  18385. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18386. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18387. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18388. }
  18389. };
  18390. Mesh.prototype.makeGeometryUnique = function () {
  18391. if (!this._geometry) {
  18392. return;
  18393. }
  18394. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18395. geometry.applyToMesh(this);
  18396. };
  18397. /**
  18398. * Sets the mesh indices.
  18399. * Expects an array populated with integers or a Int32Array.
  18400. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18401. * This method creates a new index buffer each call.
  18402. */
  18403. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18404. if (!this._geometry) {
  18405. var vertexData = new BABYLON.VertexData();
  18406. vertexData.indices = indices;
  18407. var scene = this.getScene();
  18408. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18409. }
  18410. else {
  18411. this._geometry.setIndices(indices, totalVertices);
  18412. }
  18413. };
  18414. /**
  18415. * Invert the geometry to move from a right handed system to a left handed one.
  18416. */
  18417. Mesh.prototype.toLeftHanded = function () {
  18418. if (!this._geometry) {
  18419. return;
  18420. }
  18421. this._geometry.toLeftHanded();
  18422. };
  18423. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18424. var engine = this.getScene().getEngine();
  18425. // Wireframe
  18426. var indexToBind;
  18427. if (this._unIndexed) {
  18428. indexToBind = null;
  18429. }
  18430. else {
  18431. switch (fillMode) {
  18432. case BABYLON.Material.PointFillMode:
  18433. indexToBind = null;
  18434. break;
  18435. case BABYLON.Material.WireFrameFillMode:
  18436. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18437. break;
  18438. default:
  18439. case BABYLON.Material.TriangleFillMode:
  18440. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18441. break;
  18442. }
  18443. }
  18444. // VBOs
  18445. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18446. };
  18447. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18448. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18449. return;
  18450. }
  18451. this.onBeforeDrawObservable.notifyObservers(this);
  18452. var engine = this.getScene().getEngine();
  18453. // Draw order
  18454. switch (fillMode) {
  18455. case BABYLON.Material.PointFillMode:
  18456. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18457. break;
  18458. case BABYLON.Material.WireFrameFillMode:
  18459. if (this._unIndexed) {
  18460. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18461. }
  18462. else {
  18463. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18464. }
  18465. break;
  18466. default:
  18467. if (this._unIndexed) {
  18468. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18469. }
  18470. else {
  18471. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18472. }
  18473. }
  18474. };
  18475. /**
  18476. * Registers for this mesh a javascript function called just before the rendering process.
  18477. * This function is passed the current mesh and doesn't return anything.
  18478. */
  18479. Mesh.prototype.registerBeforeRender = function (func) {
  18480. this.onBeforeRenderObservable.add(func);
  18481. };
  18482. /**
  18483. * Disposes a previously registered javascript function called before the rendering.
  18484. * This function is passed the current mesh and doesn't return anything.
  18485. */
  18486. Mesh.prototype.unregisterBeforeRender = function (func) {
  18487. this.onBeforeRenderObservable.removeCallback(func);
  18488. };
  18489. /**
  18490. * Registers for this mesh a javascript function called just after the rendering is complete.
  18491. * This function is passed the current mesh and doesn't return anything.
  18492. */
  18493. Mesh.prototype.registerAfterRender = function (func) {
  18494. this.onAfterRenderObservable.add(func);
  18495. };
  18496. /**
  18497. * Disposes a previously registered javascript function called after the rendering.
  18498. * This function is passed the current mesh and doesn't return anything.
  18499. */
  18500. Mesh.prototype.unregisterAfterRender = function (func) {
  18501. this.onAfterRenderObservable.removeCallback(func);
  18502. };
  18503. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18504. var scene = this.getScene();
  18505. this._batchCache.mustReturn = false;
  18506. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18507. this._batchCache.visibleInstances[subMeshId] = null;
  18508. if (this._visibleInstances) {
  18509. var currentRenderId = scene.getRenderId();
  18510. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18511. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18512. var selfRenderId = this._renderId;
  18513. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18514. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18515. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18516. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18517. }
  18518. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18519. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18520. this._batchCache.mustReturn = true;
  18521. return this._batchCache;
  18522. }
  18523. if (currentRenderId !== selfRenderId) {
  18524. this._batchCache.renderSelf[subMeshId] = false;
  18525. }
  18526. }
  18527. this._renderIdForInstances[subMeshId] = currentRenderId;
  18528. }
  18529. return this._batchCache;
  18530. };
  18531. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18532. var visibleInstances = batch.visibleInstances[subMesh._id];
  18533. var matricesCount = visibleInstances.length + 1;
  18534. var bufferSize = matricesCount * 16 * 4;
  18535. var currentInstancesBufferSize = this._instancesBufferSize;
  18536. var instancesBuffer = this._instancesBuffer;
  18537. while (this._instancesBufferSize < bufferSize) {
  18538. this._instancesBufferSize *= 2;
  18539. }
  18540. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18541. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18542. }
  18543. var offset = 0;
  18544. var instancesCount = 0;
  18545. var world = this.getWorldMatrix();
  18546. if (batch.renderSelf[subMesh._id]) {
  18547. world.copyToArray(this._instancesData, offset);
  18548. offset += 16;
  18549. instancesCount++;
  18550. }
  18551. if (visibleInstances) {
  18552. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18553. var instance = visibleInstances[instanceIndex];
  18554. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18555. offset += 16;
  18556. instancesCount++;
  18557. }
  18558. }
  18559. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18560. if (instancesBuffer) {
  18561. instancesBuffer.dispose();
  18562. }
  18563. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18564. this._instancesBuffer = instancesBuffer;
  18565. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18566. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18567. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18568. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18569. }
  18570. else {
  18571. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18572. }
  18573. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18574. this._draw(subMesh, fillMode, instancesCount);
  18575. engine.unbindInstanceAttributes();
  18576. };
  18577. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18578. var scene = this.getScene();
  18579. var engine = scene.getEngine();
  18580. if (hardwareInstancedRendering) {
  18581. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18582. }
  18583. else {
  18584. if (batch.renderSelf[subMesh._id]) {
  18585. // Draw
  18586. if (onBeforeDraw) {
  18587. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18588. }
  18589. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18590. }
  18591. if (batch.visibleInstances[subMesh._id]) {
  18592. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18593. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18594. // World
  18595. var world = instance.getWorldMatrix();
  18596. if (onBeforeDraw) {
  18597. onBeforeDraw(true, world, effectiveMaterial);
  18598. }
  18599. // Draw
  18600. this._draw(subMesh, fillMode);
  18601. }
  18602. }
  18603. }
  18604. };
  18605. /**
  18606. * Triggers the draw call for the mesh.
  18607. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18608. */
  18609. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18610. var scene = this.getScene();
  18611. // Managing instances
  18612. var batch = this._getInstancesRenderList(subMesh._id);
  18613. if (batch.mustReturn) {
  18614. return;
  18615. }
  18616. // Checking geometry state
  18617. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18618. return;
  18619. }
  18620. var callbackIndex;
  18621. this.onBeforeRenderObservable.notifyObservers(this);
  18622. var engine = scene.getEngine();
  18623. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18624. // Material
  18625. var effectiveMaterial = subMesh.getMaterial();
  18626. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18627. return;
  18628. }
  18629. // Outline - step 1
  18630. var savedDepthWrite = engine.getDepthWrite();
  18631. if (this.renderOutline) {
  18632. engine.setDepthWrite(false);
  18633. scene.getOutlineRenderer().render(subMesh, batch);
  18634. engine.setDepthWrite(savedDepthWrite);
  18635. }
  18636. effectiveMaterial._preBind();
  18637. var effect = effectiveMaterial.getEffect();
  18638. // Bind
  18639. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18640. this._bind(subMesh, effect, fillMode);
  18641. var world = this.getWorldMatrix();
  18642. effectiveMaterial.bind(world, this);
  18643. // Alpha mode
  18644. if (enableAlphaMode) {
  18645. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18646. }
  18647. // Draw
  18648. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18649. // Unbind
  18650. effectiveMaterial.unbind();
  18651. // Outline - step 2
  18652. if (this.renderOutline && savedDepthWrite) {
  18653. engine.setDepthWrite(true);
  18654. engine.setColorWrite(false);
  18655. scene.getOutlineRenderer().render(subMesh, batch);
  18656. engine.setColorWrite(true);
  18657. }
  18658. // Overlay
  18659. if (this.renderOverlay) {
  18660. var currentMode = engine.getAlphaMode();
  18661. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18662. scene.getOutlineRenderer().render(subMesh, batch, true);
  18663. engine.setAlphaMode(currentMode);
  18664. }
  18665. this.onAfterRenderObservable.notifyObservers(this);
  18666. };
  18667. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18668. if (isInstance) {
  18669. effectiveMaterial.bindOnlyWorldMatrix(world);
  18670. }
  18671. };
  18672. /**
  18673. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18674. */
  18675. Mesh.prototype.getEmittedParticleSystems = function () {
  18676. var results = new Array();
  18677. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18678. var particleSystem = this.getScene().particleSystems[index];
  18679. if (particleSystem.emitter === this) {
  18680. results.push(particleSystem);
  18681. }
  18682. }
  18683. return results;
  18684. };
  18685. /**
  18686. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18687. */
  18688. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18689. var results = new Array();
  18690. var descendants = this.getDescendants();
  18691. descendants.push(this);
  18692. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18693. var particleSystem = this.getScene().particleSystems[index];
  18694. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18695. results.push(particleSystem);
  18696. }
  18697. }
  18698. return results;
  18699. };
  18700. Mesh.prototype._checkDelayState = function () {
  18701. var scene = this.getScene();
  18702. if (this._geometry) {
  18703. this._geometry.load(scene);
  18704. }
  18705. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18707. this._queueLoad(this, scene);
  18708. }
  18709. };
  18710. Mesh.prototype._queueLoad = function (mesh, scene) {
  18711. var _this = this;
  18712. scene._addPendingData(mesh);
  18713. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18714. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18715. if (data instanceof ArrayBuffer) {
  18716. _this._delayLoadingFunction(data, _this);
  18717. }
  18718. else {
  18719. _this._delayLoadingFunction(JSON.parse(data), _this);
  18720. }
  18721. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18722. scene._removePendingData(_this);
  18723. }, function () { }, scene.database, getBinaryData);
  18724. };
  18725. /**
  18726. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18727. */
  18728. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18729. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18730. return false;
  18731. }
  18732. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18733. return false;
  18734. }
  18735. this._checkDelayState();
  18736. return true;
  18737. };
  18738. /**
  18739. * Sets the mesh material by the material or multiMaterial `id` property.
  18740. * The material `id` is a string identifying the material or the multiMaterial.
  18741. * This method returns nothing.
  18742. */
  18743. Mesh.prototype.setMaterialByID = function (id) {
  18744. var materials = this.getScene().materials;
  18745. var index;
  18746. for (index = 0; index < materials.length; index++) {
  18747. if (materials[index].id === id) {
  18748. this.material = materials[index];
  18749. return;
  18750. }
  18751. }
  18752. // Multi
  18753. var multiMaterials = this.getScene().multiMaterials;
  18754. for (index = 0; index < multiMaterials.length; index++) {
  18755. if (multiMaterials[index].id === id) {
  18756. this.material = multiMaterials[index];
  18757. return;
  18758. }
  18759. }
  18760. };
  18761. /**
  18762. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18763. */
  18764. Mesh.prototype.getAnimatables = function () {
  18765. var results = [];
  18766. if (this.material) {
  18767. results.push(this.material);
  18768. }
  18769. if (this.skeleton) {
  18770. results.push(this.skeleton);
  18771. }
  18772. return results;
  18773. };
  18774. /**
  18775. * Modifies the mesh geometry according to the passed transformation matrix.
  18776. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18777. * The mesh normals are modified accordingly the same transformation.
  18778. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18779. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18780. */
  18781. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18782. // Position
  18783. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18784. return;
  18785. }
  18786. var submeshes = this.subMeshes.splice(0);
  18787. this._resetPointsArrayCache();
  18788. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18789. var temp = [];
  18790. var index;
  18791. for (index = 0; index < data.length; index += 3) {
  18792. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18793. }
  18794. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18795. // Normals
  18796. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18797. return;
  18798. }
  18799. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18800. temp = [];
  18801. for (index = 0; index < data.length; index += 3) {
  18802. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18803. }
  18804. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18805. // flip faces?
  18806. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18807. this.flipFaces();
  18808. }
  18809. // Restore submeshes
  18810. this.releaseSubMeshes();
  18811. this.subMeshes = submeshes;
  18812. };
  18813. /**
  18814. * Modifies the mesh geometry according to its own current World Matrix.
  18815. * The mesh World Matrix is then reset.
  18816. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18817. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18818. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18819. */
  18820. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18821. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18822. this.scaling.copyFromFloats(1, 1, 1);
  18823. this.position.copyFromFloats(0, 0, 0);
  18824. this.rotation.copyFromFloats(0, 0, 0);
  18825. //only if quaternion is already set
  18826. if (this.rotationQuaternion) {
  18827. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18828. }
  18829. this._worldMatrix = BABYLON.Matrix.Identity();
  18830. };
  18831. // Cache
  18832. Mesh.prototype._resetPointsArrayCache = function () {
  18833. this._positions = null;
  18834. };
  18835. Mesh.prototype._generatePointsArray = function () {
  18836. if (this._positions)
  18837. return true;
  18838. this._positions = [];
  18839. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18840. if (!data) {
  18841. return false;
  18842. }
  18843. for (var index = 0; index < data.length; index += 3) {
  18844. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18845. }
  18846. return true;
  18847. };
  18848. /**
  18849. * Returns a new Mesh object generated from the current mesh properties.
  18850. * This method must not get confused with createInstance().
  18851. * The parameter `name` is a string, the name given to the new mesh.
  18852. * The optional parameter `newParent` can be any Node object (default `null`).
  18853. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18854. * 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.
  18855. */
  18856. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18857. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18858. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18859. };
  18860. /**
  18861. * Disposes the mesh.
  18862. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18863. */
  18864. Mesh.prototype.dispose = function (doNotRecurse) {
  18865. if (this._geometry) {
  18866. this._geometry.releaseForMesh(this, true);
  18867. }
  18868. // Instances
  18869. if (this._instancesBuffer) {
  18870. this._instancesBuffer.dispose();
  18871. this._instancesBuffer = null;
  18872. }
  18873. while (this.instances.length) {
  18874. this.instances[0].dispose();
  18875. }
  18876. _super.prototype.dispose.call(this, doNotRecurse);
  18877. };
  18878. /**
  18879. * Modifies the mesh geometry according to a displacement map.
  18880. * 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.
  18881. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18882. * This method returns nothing.
  18883. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18884. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18885. * 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.
  18886. */
  18887. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18888. var _this = this;
  18889. var scene = this.getScene();
  18890. var onload = function (img) {
  18891. // Getting height map data
  18892. var canvas = document.createElement("canvas");
  18893. var context = canvas.getContext("2d");
  18894. var heightMapWidth = img.width;
  18895. var heightMapHeight = img.height;
  18896. canvas.width = heightMapWidth;
  18897. canvas.height = heightMapHeight;
  18898. context.drawImage(img, 0, 0);
  18899. // Create VertexData from map data
  18900. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18901. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18902. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18903. //execute success callback, if set
  18904. if (onSuccess) {
  18905. onSuccess(_this);
  18906. }
  18907. };
  18908. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18909. };
  18910. /**
  18911. * Modifies the mesh geometry according to a displacementMap buffer.
  18912. * 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.
  18913. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18914. * This method returns nothing.
  18915. * 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.
  18916. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18917. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18918. */
  18919. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18920. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18921. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18922. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18923. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18924. return;
  18925. }
  18926. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18927. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18928. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18929. var position = BABYLON.Vector3.Zero();
  18930. var normal = BABYLON.Vector3.Zero();
  18931. var uv = BABYLON.Vector2.Zero();
  18932. for (var index = 0; index < positions.length; index += 3) {
  18933. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18934. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18935. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18936. // Compute height
  18937. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18938. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18939. var pos = (u + v * heightMapWidth) * 4;
  18940. var r = buffer[pos] / 255.0;
  18941. var g = buffer[pos + 1] / 255.0;
  18942. var b = buffer[pos + 2] / 255.0;
  18943. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18944. normal.normalize();
  18945. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18946. position = position.add(normal);
  18947. position.toArray(positions, index);
  18948. }
  18949. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18950. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18951. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18952. };
  18953. /**
  18954. * Modify the mesh to get a flat shading rendering.
  18955. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18956. * This method returns nothing.
  18957. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18958. */
  18959. Mesh.prototype.convertToFlatShadedMesh = function () {
  18960. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18961. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18962. var kinds = this.getVerticesDataKinds();
  18963. var vbs = [];
  18964. var data = [];
  18965. var newdata = [];
  18966. var updatableNormals = false;
  18967. var kindIndex;
  18968. var kind;
  18969. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18970. kind = kinds[kindIndex];
  18971. var vertexBuffer = this.getVertexBuffer(kind);
  18972. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18973. updatableNormals = vertexBuffer.isUpdatable();
  18974. kinds.splice(kindIndex, 1);
  18975. kindIndex--;
  18976. continue;
  18977. }
  18978. vbs[kind] = vertexBuffer;
  18979. data[kind] = vbs[kind].getData();
  18980. newdata[kind] = [];
  18981. }
  18982. // Save previous submeshes
  18983. var previousSubmeshes = this.subMeshes.slice(0);
  18984. var indices = this.getIndices();
  18985. var totalIndices = this.getTotalIndices();
  18986. // Generating unique vertices per face
  18987. var index;
  18988. for (index = 0; index < totalIndices; index++) {
  18989. var vertexIndex = indices[index];
  18990. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18991. kind = kinds[kindIndex];
  18992. var stride = vbs[kind].getStrideSize();
  18993. for (var offset = 0; offset < stride; offset++) {
  18994. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18995. }
  18996. }
  18997. }
  18998. // Updating faces & normal
  18999. var normals = [];
  19000. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19001. for (index = 0; index < totalIndices; index += 3) {
  19002. indices[index] = index;
  19003. indices[index + 1] = index + 1;
  19004. indices[index + 2] = index + 2;
  19005. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19006. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19007. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19008. var p1p2 = p1.subtract(p2);
  19009. var p3p2 = p3.subtract(p2);
  19010. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19011. // Store same normals for every vertex
  19012. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19013. normals.push(normal.x);
  19014. normals.push(normal.y);
  19015. normals.push(normal.z);
  19016. }
  19017. }
  19018. this.setIndices(indices);
  19019. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19020. // Updating vertex buffers
  19021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19022. kind = kinds[kindIndex];
  19023. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19024. }
  19025. // Updating submeshes
  19026. this.releaseSubMeshes();
  19027. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19028. var previousOne = previousSubmeshes[submeshIndex];
  19029. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19030. }
  19031. this.synchronizeInstances();
  19032. };
  19033. /**
  19034. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19035. * In other words, more vertices, no more indices and a single bigger VBO.
  19036. * This method returns nothing.
  19037. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19038. *
  19039. */
  19040. Mesh.prototype.convertToUnIndexedMesh = function () {
  19041. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19042. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19043. var kinds = this.getVerticesDataKinds();
  19044. var vbs = [];
  19045. var data = [];
  19046. var newdata = [];
  19047. var updatableNormals = false;
  19048. var kindIndex;
  19049. var kind;
  19050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19051. kind = kinds[kindIndex];
  19052. var vertexBuffer = this.getVertexBuffer(kind);
  19053. vbs[kind] = vertexBuffer;
  19054. data[kind] = vbs[kind].getData();
  19055. newdata[kind] = [];
  19056. }
  19057. // Save previous submeshes
  19058. var previousSubmeshes = this.subMeshes.slice(0);
  19059. var indices = this.getIndices();
  19060. var totalIndices = this.getTotalIndices();
  19061. // Generating unique vertices per face
  19062. var index;
  19063. for (index = 0; index < totalIndices; index++) {
  19064. var vertexIndex = indices[index];
  19065. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19066. kind = kinds[kindIndex];
  19067. var stride = vbs[kind].getStrideSize();
  19068. for (var offset = 0; offset < stride; offset++) {
  19069. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19070. }
  19071. }
  19072. }
  19073. // Updating indices
  19074. for (index = 0; index < totalIndices; index += 3) {
  19075. indices[index] = index;
  19076. indices[index + 1] = index + 1;
  19077. indices[index + 2] = index + 2;
  19078. }
  19079. this.setIndices(indices);
  19080. // Updating vertex buffers
  19081. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19082. kind = kinds[kindIndex];
  19083. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19084. }
  19085. // Updating submeshes
  19086. this.releaseSubMeshes();
  19087. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19088. var previousOne = previousSubmeshes[submeshIndex];
  19089. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19090. }
  19091. this._unIndexed = true;
  19092. this.synchronizeInstances();
  19093. };
  19094. /**
  19095. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19096. * This method returns nothing.
  19097. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19098. */
  19099. Mesh.prototype.flipFaces = function (flipNormals) {
  19100. if (flipNormals === void 0) { flipNormals = false; }
  19101. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19102. var i;
  19103. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19104. for (i = 0; i < vertex_data.normals.length; i++) {
  19105. vertex_data.normals[i] *= -1;
  19106. }
  19107. }
  19108. var temp;
  19109. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19110. // reassign indices
  19111. temp = vertex_data.indices[i + 1];
  19112. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19113. vertex_data.indices[i + 2] = temp;
  19114. }
  19115. vertex_data.applyToMesh(this);
  19116. };
  19117. // Instances
  19118. /**
  19119. * Creates a new InstancedMesh object from the mesh model.
  19120. * An instance shares the same properties and the same material than its model.
  19121. * Only these properties of each instance can then be set individually :
  19122. * - position
  19123. * - rotation
  19124. * - rotationQuaternion
  19125. * - setPivotMatrix
  19126. * - scaling
  19127. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19128. * Warning : this method is not supported for Line mesh and LineSystem
  19129. */
  19130. Mesh.prototype.createInstance = function (name) {
  19131. return new BABYLON.InstancedMesh(name, this);
  19132. };
  19133. /**
  19134. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19135. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19136. * This method returns nothing.
  19137. */
  19138. Mesh.prototype.synchronizeInstances = function () {
  19139. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19140. var instance = this.instances[instanceIndex];
  19141. instance._syncSubMeshes();
  19142. }
  19143. };
  19144. /**
  19145. * Simplify the mesh according to the given array of settings.
  19146. * Function will return immediately and will simplify async. It returns nothing.
  19147. * @param settings a collection of simplification settings.
  19148. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19149. * @param type the type of simplification to run.
  19150. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19151. */
  19152. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19153. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19154. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19155. this.getScene().simplificationQueue.addTask({
  19156. settings: settings,
  19157. parallelProcessing: parallelProcessing,
  19158. mesh: this,
  19159. simplificationType: simplificationType,
  19160. successCallback: successCallback
  19161. });
  19162. };
  19163. /**
  19164. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19165. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19166. * This should be used together with the simplification to avoid disappearing triangles.
  19167. * @param successCallback an optional success callback to be called after the optimization finished.
  19168. */
  19169. Mesh.prototype.optimizeIndices = function (successCallback) {
  19170. var _this = this;
  19171. var indices = this.getIndices();
  19172. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19173. var vectorPositions = [];
  19174. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19175. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19176. }
  19177. var dupes = [];
  19178. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19179. var realPos = vectorPositions.length - 1 - iteration;
  19180. var testedPosition = vectorPositions[realPos];
  19181. for (var j = 0; j < realPos; ++j) {
  19182. var againstPosition = vectorPositions[j];
  19183. if (testedPosition.equals(againstPosition)) {
  19184. dupes[realPos] = j;
  19185. break;
  19186. }
  19187. }
  19188. }, function () {
  19189. for (var i = 0; i < indices.length; ++i) {
  19190. indices[i] = dupes[indices[i]] || indices[i];
  19191. }
  19192. //indices are now reordered
  19193. var originalSubMeshes = _this.subMeshes.slice(0);
  19194. _this.setIndices(indices);
  19195. _this.subMeshes = originalSubMeshes;
  19196. if (successCallback) {
  19197. successCallback(_this);
  19198. }
  19199. });
  19200. };
  19201. // Statics
  19202. /**
  19203. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19204. * The parameter `parsedMesh` is the mesh to be copied.
  19205. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19206. */
  19207. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19208. var mesh = new Mesh(parsedMesh.name, scene);
  19209. mesh.id = parsedMesh.id;
  19210. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19211. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19212. if (parsedMesh.rotationQuaternion) {
  19213. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19214. }
  19215. else if (parsedMesh.rotation) {
  19216. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19217. }
  19218. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19219. if (parsedMesh.localMatrix) {
  19220. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19221. }
  19222. else if (parsedMesh.pivotMatrix) {
  19223. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19224. }
  19225. mesh.setEnabled(parsedMesh.isEnabled);
  19226. mesh.isVisible = parsedMesh.isVisible;
  19227. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19228. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19229. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19230. if (parsedMesh.applyFog !== undefined) {
  19231. mesh.applyFog = parsedMesh.applyFog;
  19232. }
  19233. if (parsedMesh.pickable !== undefined) {
  19234. mesh.isPickable = parsedMesh.pickable;
  19235. }
  19236. if (parsedMesh.alphaIndex !== undefined) {
  19237. mesh.alphaIndex = parsedMesh.alphaIndex;
  19238. }
  19239. mesh.receiveShadows = parsedMesh.receiveShadows;
  19240. mesh.billboardMode = parsedMesh.billboardMode;
  19241. if (parsedMesh.visibility !== undefined) {
  19242. mesh.visibility = parsedMesh.visibility;
  19243. }
  19244. mesh.checkCollisions = parsedMesh.checkCollisions;
  19245. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19246. // freezeWorldMatrix
  19247. if (parsedMesh.freezeWorldMatrix) {
  19248. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19249. }
  19250. // Parent
  19251. if (parsedMesh.parentId) {
  19252. mesh._waitingParentId = parsedMesh.parentId;
  19253. }
  19254. // Actions
  19255. if (parsedMesh.actions !== undefined) {
  19256. mesh._waitingActions = parsedMesh.actions;
  19257. }
  19258. // Geometry
  19259. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19260. if (parsedMesh.delayLoadingFile) {
  19261. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19262. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19263. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19264. if (parsedMesh._binaryInfo) {
  19265. mesh._binaryInfo = parsedMesh._binaryInfo;
  19266. }
  19267. mesh._delayInfo = [];
  19268. if (parsedMesh.hasUVs) {
  19269. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19270. }
  19271. if (parsedMesh.hasUVs2) {
  19272. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19273. }
  19274. if (parsedMesh.hasUVs3) {
  19275. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19276. }
  19277. if (parsedMesh.hasUVs4) {
  19278. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19279. }
  19280. if (parsedMesh.hasUVs5) {
  19281. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19282. }
  19283. if (parsedMesh.hasUVs6) {
  19284. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19285. }
  19286. if (parsedMesh.hasColors) {
  19287. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19288. }
  19289. if (parsedMesh.hasMatricesIndices) {
  19290. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19291. }
  19292. if (parsedMesh.hasMatricesWeights) {
  19293. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19294. }
  19295. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19296. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19297. mesh._checkDelayState();
  19298. }
  19299. }
  19300. else {
  19301. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19302. }
  19303. // Material
  19304. if (parsedMesh.materialId) {
  19305. mesh.setMaterialByID(parsedMesh.materialId);
  19306. }
  19307. else {
  19308. mesh.material = null;
  19309. }
  19310. // Skeleton
  19311. if (parsedMesh.skeletonId > -1) {
  19312. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19313. if (parsedMesh.numBoneInfluencers) {
  19314. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19315. }
  19316. }
  19317. // Animations
  19318. if (parsedMesh.animations) {
  19319. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19320. var parsedAnimation = parsedMesh.animations[animationIndex];
  19321. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19322. }
  19323. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19324. }
  19325. if (parsedMesh.autoAnimate) {
  19326. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19327. }
  19328. // Layer Mask
  19329. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19330. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19331. }
  19332. else {
  19333. mesh.layerMask = 0x0FFFFFFF;
  19334. }
  19335. //(Deprecated) physics
  19336. if (parsedMesh.physicsImpostor) {
  19337. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19338. mass: parsedMesh.physicsMass,
  19339. friction: parsedMesh.physicsFriction,
  19340. restitution: parsedMesh.physicsRestitution
  19341. }, scene);
  19342. }
  19343. // Instances
  19344. if (parsedMesh.instances) {
  19345. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19346. var parsedInstance = parsedMesh.instances[index];
  19347. var instance = mesh.createInstance(parsedInstance.name);
  19348. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19349. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19350. if (parsedInstance.rotationQuaternion) {
  19351. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19352. }
  19353. else if (parsedInstance.rotation) {
  19354. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19355. }
  19356. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19357. instance.checkCollisions = mesh.checkCollisions;
  19358. if (parsedMesh.animations) {
  19359. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19360. parsedAnimation = parsedMesh.animations[animationIndex];
  19361. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19362. }
  19363. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19364. }
  19365. }
  19366. }
  19367. return mesh;
  19368. };
  19369. /**
  19370. * Creates a ribbon mesh.
  19371. * Please consider using the same method from the MeshBuilder class instead.
  19372. * 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.
  19373. *
  19374. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19375. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19376. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19377. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19378. * 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.
  19379. * 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.
  19380. * 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
  19381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19384. */
  19385. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19386. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19387. pathArray: pathArray,
  19388. closeArray: closeArray,
  19389. closePath: closePath,
  19390. offset: offset,
  19391. updatable: updatable,
  19392. sideOrientation: sideOrientation,
  19393. instance: instance
  19394. }, scene);
  19395. };
  19396. /**
  19397. * Creates a plane polygonal mesh. By default, this is a disc.
  19398. * Please consider using the same method from the MeshBuilder class instead.
  19399. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19400. * 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.
  19401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19404. */
  19405. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19406. var options = {
  19407. radius: radius,
  19408. tessellation: tessellation,
  19409. sideOrientation: sideOrientation,
  19410. updatable: updatable
  19411. };
  19412. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19413. };
  19414. /**
  19415. * Creates a box mesh.
  19416. * Please consider using the same method from the MeshBuilder class instead.
  19417. * The parameter `size` sets the size (float) of each box side (default 1).
  19418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19421. */
  19422. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19423. var options = {
  19424. size: size,
  19425. sideOrientation: sideOrientation,
  19426. updatable: updatable
  19427. };
  19428. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19429. };
  19430. /**
  19431. * Creates a sphere mesh.
  19432. * Please consider using the same method from the MeshBuilder class instead.
  19433. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19434. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19438. */
  19439. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19440. var options = {
  19441. segments: segments,
  19442. diameterX: diameter,
  19443. diameterY: diameter,
  19444. diameterZ: diameter,
  19445. sideOrientation: sideOrientation,
  19446. updatable: updatable
  19447. };
  19448. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19449. };
  19450. /**
  19451. * Creates a cylinder or a cone mesh.
  19452. * Please consider using the same method from the MeshBuilder class instead.
  19453. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19454. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19455. * 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.
  19456. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19457. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19461. */
  19462. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19463. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19464. if (scene !== undefined) {
  19465. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19466. updatable = scene;
  19467. }
  19468. scene = subdivisions;
  19469. subdivisions = 1;
  19470. }
  19471. var options = {
  19472. height: height,
  19473. diameterTop: diameterTop,
  19474. diameterBottom: diameterBottom,
  19475. tessellation: tessellation,
  19476. subdivisions: subdivisions,
  19477. sideOrientation: sideOrientation,
  19478. updatable: updatable
  19479. };
  19480. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19481. };
  19482. // Torus (Code from SharpDX.org)
  19483. /**
  19484. * Creates a torus mesh.
  19485. * Please consider using the same method from the MeshBuilder class instead.
  19486. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19487. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19488. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19492. */
  19493. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19494. var options = {
  19495. diameter: diameter,
  19496. thickness: thickness,
  19497. tessellation: tessellation,
  19498. sideOrientation: sideOrientation,
  19499. updatable: updatable
  19500. };
  19501. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19502. };
  19503. /**
  19504. * Creates a torus knot mesh.
  19505. * Please consider using the same method from the MeshBuilder class instead.
  19506. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19507. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19508. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19509. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19513. */
  19514. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19515. var options = {
  19516. radius: radius,
  19517. tube: tube,
  19518. radialSegments: radialSegments,
  19519. tubularSegments: tubularSegments,
  19520. p: p,
  19521. q: q,
  19522. sideOrientation: sideOrientation,
  19523. updatable: updatable
  19524. };
  19525. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19526. };
  19527. /**
  19528. * Creates a line mesh.
  19529. * Please consider using the same method from the MeshBuilder class instead.
  19530. * 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.
  19531. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19532. * The parameter `points` is an array successive Vector3.
  19533. * 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
  19534. * When updating an instance, remember that only point positions can change, not the number of points.
  19535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19536. */
  19537. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19538. var options = {
  19539. points: points,
  19540. updatable: updatable,
  19541. instance: instance
  19542. };
  19543. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19544. };
  19545. /**
  19546. * Creates a dashed line mesh.
  19547. * Please consider using the same method from the MeshBuilder class instead.
  19548. * 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.
  19549. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19550. * The parameter `points` is an array successive Vector3.
  19551. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19552. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19553. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19554. * 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
  19555. * When updating an instance, remember that only point positions can change, not the number of points.
  19556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19557. */
  19558. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19559. var options = {
  19560. points: points,
  19561. dashSize: dashSize,
  19562. gapSize: gapSize,
  19563. dashNb: dashNb,
  19564. updatable: updatable
  19565. };
  19566. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19567. };
  19568. /**
  19569. * Creates an extruded shape mesh.
  19570. * 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.
  19571. * Please consider using the same method from the MeshBuilder class instead.
  19572. *
  19573. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19574. * 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
  19575. * extruded along the Z axis.
  19576. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19577. * 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.
  19578. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19579. * 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
  19580. * 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
  19581. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19585. */
  19586. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19587. var options = {
  19588. shape: shape,
  19589. path: path,
  19590. scale: scale,
  19591. rotation: rotation,
  19592. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19593. sideOrientation: sideOrientation,
  19594. instance: instance,
  19595. updatable: updatable
  19596. };
  19597. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19598. };
  19599. /**
  19600. * Creates an custom extruded shape mesh.
  19601. * 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.
  19602. * Please consider using the same method from the MeshBuilder class instead.
  19603. *
  19604. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19605. * 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
  19606. * extruded along the Z axis.
  19607. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19608. * 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
  19609. * and the distance of this point from the begining of the path :
  19610. * ```javascript
  19611. * var rotationFunction = function(i, distance) {
  19612. * // do things
  19613. * return rotationValue; }
  19614. * ```
  19615. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19616. * 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
  19617. * and the distance of this point from the begining of the path :
  19618. * ```javascript
  19619. * var scaleFunction = function(i, distance) {
  19620. * // do things
  19621. * return scaleValue;}
  19622. * ```
  19623. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19624. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19625. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19626. * 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
  19627. * 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
  19628. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19632. */
  19633. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19634. var options = {
  19635. shape: shape,
  19636. path: path,
  19637. scaleFunction: scaleFunction,
  19638. rotationFunction: rotationFunction,
  19639. ribbonCloseArray: ribbonCloseArray,
  19640. ribbonClosePath: ribbonClosePath,
  19641. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19642. sideOrientation: sideOrientation,
  19643. instance: instance,
  19644. updatable: updatable
  19645. };
  19646. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19647. };
  19648. /**
  19649. * Creates lathe mesh.
  19650. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19651. * Please consider using the same method from the MeshBuilder class instead.
  19652. * 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
  19653. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19654. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19655. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19657. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19659. */
  19660. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19661. var options = {
  19662. shape: shape,
  19663. radius: radius,
  19664. tessellation: tessellation,
  19665. sideOrientation: sideOrientation,
  19666. updatable: updatable
  19667. };
  19668. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19669. };
  19670. /**
  19671. * Creates a plane mesh.
  19672. * Please consider using the same method from the MeshBuilder class instead.
  19673. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19677. */
  19678. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19679. var options = {
  19680. size: size,
  19681. width: size,
  19682. height: size,
  19683. sideOrientation: sideOrientation,
  19684. updatable: updatable
  19685. };
  19686. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19687. };
  19688. /**
  19689. * Creates a ground mesh.
  19690. * Please consider using the same method from the MeshBuilder class instead.
  19691. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19692. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19694. */
  19695. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19696. var options = {
  19697. width: width,
  19698. height: height,
  19699. subdivisions: subdivisions,
  19700. updatable: updatable
  19701. };
  19702. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19703. };
  19704. /**
  19705. * Creates a tiled ground mesh.
  19706. * Please consider using the same method from the MeshBuilder class instead.
  19707. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19708. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19709. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19710. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19711. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19712. * numbers of subdivisions on the ground width and height of each tile.
  19713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19714. */
  19715. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19716. var options = {
  19717. xmin: xmin,
  19718. zmin: zmin,
  19719. xmax: xmax,
  19720. zmax: zmax,
  19721. subdivisions: subdivisions,
  19722. precision: precision,
  19723. updatable: updatable
  19724. };
  19725. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19726. };
  19727. /**
  19728. * Creates a ground mesh from a height map.
  19729. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19730. * Please consider using the same method from the MeshBuilder class instead.
  19731. * The parameter `url` sets the URL of the height map image resource.
  19732. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19733. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19734. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19735. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19736. * 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).
  19737. * This function is passed the newly built mesh :
  19738. * ```javascript
  19739. * function(mesh) { // do things
  19740. * return; }
  19741. * ```
  19742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19743. */
  19744. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19745. var options = {
  19746. width: width,
  19747. height: height,
  19748. subdivisions: subdivisions,
  19749. minHeight: minHeight,
  19750. maxHeight: maxHeight,
  19751. updatable: updatable,
  19752. onReady: onReady
  19753. };
  19754. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19755. };
  19756. /**
  19757. * Creates a tube mesh.
  19758. * 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.
  19759. * Please consider using the same method from the MeshBuilder class instead.
  19760. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19761. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19762. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19763. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19764. * 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.
  19765. * It must return a radius value (positive float) :
  19766. * ```javascript
  19767. * var radiusFunction = function(i, distance) {
  19768. * // do things
  19769. * return radius; }
  19770. * ```
  19771. * 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
  19772. * 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
  19773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19776. */
  19777. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19778. var options = {
  19779. path: path,
  19780. radius: radius,
  19781. tessellation: tessellation,
  19782. radiusFunction: radiusFunction,
  19783. arc: 1,
  19784. cap: cap,
  19785. updatable: updatable,
  19786. sideOrientation: sideOrientation,
  19787. instance: instance
  19788. };
  19789. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19790. };
  19791. /**
  19792. * Creates a polyhedron mesh.
  19793. * Please consider using the same method from the MeshBuilder class instead.
  19794. * 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
  19795. * to choose the wanted type.
  19796. * The parameter `size` (positive float, default 1) sets the polygon size.
  19797. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19798. * 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`.
  19799. * 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
  19800. * 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)`).
  19801. * 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
  19802. * 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.
  19803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19806. */
  19807. Mesh.CreatePolyhedron = function (name, options, scene) {
  19808. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19809. };
  19810. /**
  19811. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19812. * Please consider using the same method from the MeshBuilder class instead.
  19813. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19814. * 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`).
  19815. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19816. * 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.
  19817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19820. */
  19821. Mesh.CreateIcoSphere = function (name, options, scene) {
  19822. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19823. };
  19824. /**
  19825. * Creates a decal mesh.
  19826. * Please consider using the same method from the MeshBuilder class instead.
  19827. * 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.
  19828. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19829. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19830. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19831. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19832. */
  19833. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19834. var options = {
  19835. position: position,
  19836. normal: normal,
  19837. size: size,
  19838. angle: angle
  19839. };
  19840. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19841. };
  19842. // Skeletons
  19843. /**
  19844. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19845. */
  19846. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19847. var source;
  19848. if (!this._sourcePositions) {
  19849. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19850. this._sourcePositions = new Float32Array(source);
  19851. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19852. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19853. }
  19854. }
  19855. return this._sourcePositions;
  19856. };
  19857. /**
  19858. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19859. */
  19860. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19861. var source;
  19862. if (!this._sourceNormals) {
  19863. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19864. this._sourceNormals = new Float32Array(source);
  19865. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19866. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19867. }
  19868. }
  19869. return this._sourceNormals;
  19870. };
  19871. /**
  19872. * Update the vertex buffers by applying transformation from the bones
  19873. * @param {skeleton} skeleton to apply
  19874. */
  19875. Mesh.prototype.applySkeleton = function (skeleton) {
  19876. if (!this.geometry) {
  19877. return;
  19878. }
  19879. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19880. return;
  19881. }
  19882. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19883. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19884. return this;
  19885. }
  19886. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19887. return this;
  19888. }
  19889. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19890. return this;
  19891. }
  19892. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19893. return this;
  19894. }
  19895. if (!this._sourcePositions) {
  19896. this.setPositionsForCPUSkinning();
  19897. }
  19898. if (!this._sourceNormals) {
  19899. this.setNormalsForCPUSkinning();
  19900. }
  19901. // positionsData checks for not being Float32Array will only pass at most once
  19902. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19903. if (!(positionsData instanceof Float32Array)) {
  19904. positionsData = new Float32Array(positionsData);
  19905. }
  19906. // normalsData checks for not being Float32Array will only pass at most once
  19907. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19908. if (!(normalsData instanceof Float32Array)) {
  19909. normalsData = new Float32Array(normalsData);
  19910. }
  19911. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19912. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19913. var needExtras = this.numBoneInfluencers > 4;
  19914. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19915. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19916. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19917. var tempVector3 = BABYLON.Vector3.Zero();
  19918. var finalMatrix = new BABYLON.Matrix();
  19919. var tempMatrix = new BABYLON.Matrix();
  19920. var matWeightIdx = 0;
  19921. var inf;
  19922. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19923. var weight;
  19924. for (inf = 0; inf < 4; inf++) {
  19925. weight = matricesWeightsData[matWeightIdx + inf];
  19926. if (weight > 0) {
  19927. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19928. finalMatrix.addToSelf(tempMatrix);
  19929. }
  19930. else
  19931. break;
  19932. }
  19933. if (needExtras) {
  19934. for (inf = 0; inf < 4; inf++) {
  19935. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19936. if (weight > 0) {
  19937. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19938. finalMatrix.addToSelf(tempMatrix);
  19939. }
  19940. else
  19941. break;
  19942. }
  19943. }
  19944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19945. tempVector3.toArray(positionsData, index);
  19946. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19947. tempVector3.toArray(normalsData, index);
  19948. finalMatrix.reset();
  19949. }
  19950. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19951. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19952. return this;
  19953. };
  19954. // Tools
  19955. /**
  19956. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  19957. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19958. */
  19959. Mesh.MinMax = function (meshes) {
  19960. var minVector = null;
  19961. var maxVector = null;
  19962. for (var i in meshes) {
  19963. var mesh = meshes[i];
  19964. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19965. if (!minVector) {
  19966. minVector = boundingBox.minimumWorld;
  19967. maxVector = boundingBox.maximumWorld;
  19968. continue;
  19969. }
  19970. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19971. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19972. }
  19973. return {
  19974. min: minVector,
  19975. max: maxVector
  19976. };
  19977. };
  19978. /**
  19979. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  19980. */
  19981. Mesh.Center = function (meshesOrMinMaxVector) {
  19982. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19983. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19984. };
  19985. /**
  19986. * Merge the array of meshes into a single mesh for performance reasons.
  19987. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19988. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19989. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19990. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19991. */
  19992. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19993. if (disposeSource === void 0) { disposeSource = true; }
  19994. var index;
  19995. if (!allow32BitsIndices) {
  19996. var totalVertices = 0;
  19997. // Counting vertices
  19998. for (index = 0; index < meshes.length; index++) {
  19999. if (meshes[index]) {
  20000. totalVertices += meshes[index].getTotalVertices();
  20001. if (totalVertices > 65536) {
  20002. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20003. return null;
  20004. }
  20005. }
  20006. }
  20007. }
  20008. // Merge
  20009. var vertexData;
  20010. var otherVertexData;
  20011. var source;
  20012. for (index = 0; index < meshes.length; index++) {
  20013. if (meshes[index]) {
  20014. meshes[index].computeWorldMatrix(true);
  20015. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20016. otherVertexData.transform(meshes[index].getWorldMatrix());
  20017. if (vertexData) {
  20018. vertexData.merge(otherVertexData);
  20019. }
  20020. else {
  20021. vertexData = otherVertexData;
  20022. source = meshes[index];
  20023. }
  20024. }
  20025. }
  20026. if (!meshSubclass) {
  20027. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20028. }
  20029. vertexData.applyToMesh(meshSubclass);
  20030. // Setting properties
  20031. meshSubclass.material = source.material;
  20032. meshSubclass.checkCollisions = source.checkCollisions;
  20033. // Cleaning
  20034. if (disposeSource) {
  20035. for (index = 0; index < meshes.length; index++) {
  20036. if (meshes[index]) {
  20037. meshes[index].dispose();
  20038. }
  20039. }
  20040. }
  20041. return meshSubclass;
  20042. };
  20043. // Consts
  20044. Mesh._FRONTSIDE = 0;
  20045. Mesh._BACKSIDE = 1;
  20046. Mesh._DOUBLESIDE = 2;
  20047. Mesh._DEFAULTSIDE = 0;
  20048. Mesh._NO_CAP = 0;
  20049. Mesh._CAP_START = 1;
  20050. Mesh._CAP_END = 2;
  20051. Mesh._CAP_ALL = 3;
  20052. return Mesh;
  20053. })(BABYLON.AbstractMesh);
  20054. BABYLON.Mesh = Mesh;
  20055. })(BABYLON || (BABYLON = {}));
  20056. var BABYLON;
  20057. (function (BABYLON) {
  20058. var SubMesh = (function () {
  20059. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20060. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20061. this.materialIndex = materialIndex;
  20062. this.verticesStart = verticesStart;
  20063. this.verticesCount = verticesCount;
  20064. this.indexStart = indexStart;
  20065. this.indexCount = indexCount;
  20066. this._renderId = 0;
  20067. this._mesh = mesh;
  20068. this._renderingMesh = renderingMesh || mesh;
  20069. mesh.subMeshes.push(this);
  20070. this._trianglePlanes = [];
  20071. this._id = mesh.subMeshes.length - 1;
  20072. if (createBoundingBox) {
  20073. this.refreshBoundingInfo();
  20074. mesh.computeWorldMatrix(true);
  20075. }
  20076. }
  20077. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20078. get: function () {
  20079. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. SubMesh.prototype.getBoundingInfo = function () {
  20085. if (this.IsGlobal) {
  20086. return this._mesh.getBoundingInfo();
  20087. }
  20088. return this._boundingInfo;
  20089. };
  20090. SubMesh.prototype.getMesh = function () {
  20091. return this._mesh;
  20092. };
  20093. SubMesh.prototype.getRenderingMesh = function () {
  20094. return this._renderingMesh;
  20095. };
  20096. SubMesh.prototype.getMaterial = function () {
  20097. var rootMaterial = this._renderingMesh.material;
  20098. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20099. var multiMaterial = rootMaterial;
  20100. return multiMaterial.getSubMaterial(this.materialIndex);
  20101. }
  20102. if (!rootMaterial) {
  20103. return this._mesh.getScene().defaultMaterial;
  20104. }
  20105. return rootMaterial;
  20106. };
  20107. // Methods
  20108. SubMesh.prototype.refreshBoundingInfo = function () {
  20109. this._lastColliderWorldVertices = null;
  20110. if (this.IsGlobal) {
  20111. return;
  20112. }
  20113. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20114. if (!data) {
  20115. this._boundingInfo = this._mesh._boundingInfo;
  20116. return;
  20117. }
  20118. var indices = this._renderingMesh.getIndices();
  20119. var extend;
  20120. //is this the only submesh?
  20121. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20122. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20123. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20124. }
  20125. else {
  20126. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20127. }
  20128. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20129. };
  20130. SubMesh.prototype._checkCollision = function (collider) {
  20131. return this.getBoundingInfo()._checkCollision(collider);
  20132. };
  20133. SubMesh.prototype.updateBoundingInfo = function (world) {
  20134. if (!this.getBoundingInfo()) {
  20135. this.refreshBoundingInfo();
  20136. }
  20137. this.getBoundingInfo().update(world);
  20138. };
  20139. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20140. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20141. };
  20142. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20143. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20144. };
  20145. SubMesh.prototype.render = function (enableAlphaMode) {
  20146. this._renderingMesh.render(this, enableAlphaMode);
  20147. };
  20148. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20149. if (!this._linesIndexBuffer) {
  20150. var linesIndices = [];
  20151. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20152. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20153. }
  20154. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20155. this.linesIndexCount = linesIndices.length;
  20156. }
  20157. return this._linesIndexBuffer;
  20158. };
  20159. SubMesh.prototype.canIntersects = function (ray) {
  20160. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20161. };
  20162. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20163. var intersectInfo = null;
  20164. // LineMesh first as it's also a Mesh...
  20165. if (this._mesh instanceof BABYLON.LinesMesh) {
  20166. var lineMesh = this._mesh;
  20167. // Line test
  20168. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20169. var p0 = positions[indices[index]];
  20170. var p1 = positions[indices[index + 1]];
  20171. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20172. if (length < 0) {
  20173. continue;
  20174. }
  20175. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20176. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20177. if (fastCheck) {
  20178. break;
  20179. }
  20180. }
  20181. }
  20182. }
  20183. else {
  20184. // Triangles test
  20185. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20186. var p0 = positions[indices[index]];
  20187. var p1 = positions[indices[index + 1]];
  20188. var p2 = positions[indices[index + 2]];
  20189. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20190. if (currentIntersectInfo) {
  20191. if (currentIntersectInfo.distance < 0) {
  20192. continue;
  20193. }
  20194. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20195. intersectInfo = currentIntersectInfo;
  20196. intersectInfo.faceId = index / 3;
  20197. if (fastCheck) {
  20198. break;
  20199. }
  20200. }
  20201. }
  20202. }
  20203. }
  20204. return intersectInfo;
  20205. };
  20206. // Clone
  20207. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20208. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20209. if (!this.IsGlobal) {
  20210. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20211. }
  20212. return result;
  20213. };
  20214. // Dispose
  20215. SubMesh.prototype.dispose = function () {
  20216. if (this._linesIndexBuffer) {
  20217. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20218. this._linesIndexBuffer = null;
  20219. }
  20220. // Remove from mesh
  20221. var index = this._mesh.subMeshes.indexOf(this);
  20222. this._mesh.subMeshes.splice(index, 1);
  20223. };
  20224. // Statics
  20225. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20226. var minVertexIndex = Number.MAX_VALUE;
  20227. var maxVertexIndex = -Number.MAX_VALUE;
  20228. renderingMesh = renderingMesh || mesh;
  20229. var indices = renderingMesh.getIndices();
  20230. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20231. var vertexIndex = indices[index];
  20232. if (vertexIndex < minVertexIndex)
  20233. minVertexIndex = vertexIndex;
  20234. if (vertexIndex > maxVertexIndex)
  20235. maxVertexIndex = vertexIndex;
  20236. }
  20237. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20238. };
  20239. return SubMesh;
  20240. })();
  20241. BABYLON.SubMesh = SubMesh;
  20242. })(BABYLON || (BABYLON = {}));
  20243. var BABYLON;
  20244. (function (BABYLON) {
  20245. var MeshBuilder = (function () {
  20246. function MeshBuilder() {
  20247. }
  20248. /**
  20249. * Creates a box mesh.
  20250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20251. * The parameter `size` sets the size (float) of each box side (default 1).
  20252. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20253. * 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).
  20254. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20258. */
  20259. MeshBuilder.CreateBox = function (name, options, scene) {
  20260. var box = new BABYLON.Mesh(name, scene);
  20261. var vertexData = BABYLON.VertexData.CreateBox(options);
  20262. vertexData.applyToMesh(box, options.updatable);
  20263. return box;
  20264. };
  20265. /**
  20266. * Creates a sphere mesh.
  20267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20268. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20269. * 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`).
  20270. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20271. * 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
  20272. * 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).
  20273. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20274. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20276. */
  20277. MeshBuilder.CreateSphere = function (name, options, scene) {
  20278. var sphere = new BABYLON.Mesh(name, scene);
  20279. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20280. vertexData.applyToMesh(sphere, options.updatable);
  20281. return sphere;
  20282. };
  20283. /**
  20284. * Creates a plane polygonal mesh. By default, this is a disc.
  20285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20286. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20287. * 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.
  20288. * 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
  20289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20292. */
  20293. MeshBuilder.CreateDisc = function (name, options, scene) {
  20294. var disc = new BABYLON.Mesh(name, scene);
  20295. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20296. vertexData.applyToMesh(disc, options.updatable);
  20297. return disc;
  20298. };
  20299. /**
  20300. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20301. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20302. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20303. * 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`).
  20304. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20305. * 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.
  20306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20309. */
  20310. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20311. var sphere = new BABYLON.Mesh(name, scene);
  20312. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20313. vertexData.applyToMesh(sphere, options.updatable);
  20314. return sphere;
  20315. };
  20316. ;
  20317. /**
  20318. * Creates a ribbon mesh.
  20319. * 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.
  20320. *
  20321. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20322. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20323. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20324. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20325. * 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.
  20326. * 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.
  20327. * 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
  20328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20330. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20332. */
  20333. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20334. var pathArray = options.pathArray;
  20335. var closeArray = options.closeArray;
  20336. var closePath = options.closePath;
  20337. var offset = options.offset;
  20338. var sideOrientation = options.sideOrientation;
  20339. var instance = options.instance;
  20340. var updatable = options.updatable;
  20341. if (instance) {
  20342. // positionFunction : ribbon case
  20343. // only pathArray and sideOrientation parameters are taken into account for positions update
  20344. var positionFunction = function (positions) {
  20345. var minlg = pathArray[0].length;
  20346. var i = 0;
  20347. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20348. for (var si = 1; si <= ns; si++) {
  20349. for (var p = 0; p < pathArray.length; p++) {
  20350. var path = pathArray[p];
  20351. var l = path.length;
  20352. minlg = (minlg < l) ? minlg : l;
  20353. var j = 0;
  20354. while (j < minlg) {
  20355. positions[i] = path[j].x;
  20356. positions[i + 1] = path[j].y;
  20357. positions[i + 2] = path[j].z;
  20358. j++;
  20359. i += 3;
  20360. }
  20361. if (instance._closePath) {
  20362. positions[i] = path[0].x;
  20363. positions[i + 1] = path[0].y;
  20364. positions[i + 2] = path[0].z;
  20365. i += 3;
  20366. }
  20367. }
  20368. }
  20369. };
  20370. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20371. positionFunction(positions);
  20372. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20373. if (!(instance.areNormalsFrozen)) {
  20374. var indices = instance.getIndices();
  20375. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20376. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20377. if (instance._closePath) {
  20378. var indexFirst = 0;
  20379. var indexLast = 0;
  20380. for (var p = 0; p < pathArray.length; p++) {
  20381. indexFirst = instance._idx[p] * 3;
  20382. if (p + 1 < pathArray.length) {
  20383. indexLast = (instance._idx[p + 1] - 1) * 3;
  20384. }
  20385. else {
  20386. indexLast = normals.length - 3;
  20387. }
  20388. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20389. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20390. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20391. normals[indexLast] = normals[indexFirst];
  20392. normals[indexLast + 1] = normals[indexFirst + 1];
  20393. normals[indexLast + 2] = normals[indexFirst + 2];
  20394. }
  20395. }
  20396. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20397. }
  20398. return instance;
  20399. }
  20400. else {
  20401. var ribbon = new BABYLON.Mesh(name, scene);
  20402. ribbon.sideOrientation = sideOrientation;
  20403. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20404. if (closePath) {
  20405. ribbon._idx = vertexData._idx;
  20406. }
  20407. ribbon._closePath = closePath;
  20408. ribbon._closeArray = closeArray;
  20409. vertexData.applyToMesh(ribbon, updatable);
  20410. return ribbon;
  20411. }
  20412. };
  20413. /**
  20414. * Creates a cylinder or a cone mesh.
  20415. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20416. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20417. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20418. * 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.
  20419. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20420. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20421. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20422. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20423. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20424. * 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).
  20425. * 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
  20426. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20427. * 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
  20428. * 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.
  20429. * If `enclose` is false, a ring surface is one element.
  20430. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20431. * 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
  20432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20435. */
  20436. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20437. var cylinder = new BABYLON.Mesh(name, scene);
  20438. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20439. vertexData.applyToMesh(cylinder, options.updatable);
  20440. return cylinder;
  20441. };
  20442. /**
  20443. * Creates a torus mesh.
  20444. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20445. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20446. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20447. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20451. */
  20452. MeshBuilder.CreateTorus = function (name, options, scene) {
  20453. var torus = new BABYLON.Mesh(name, scene);
  20454. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20455. vertexData.applyToMesh(torus, options.updatable);
  20456. return torus;
  20457. };
  20458. /**
  20459. * Creates a torus knot mesh.
  20460. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20461. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20462. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20463. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20464. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20468. */
  20469. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20470. var torusKnot = new BABYLON.Mesh(name, scene);
  20471. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20472. vertexData.applyToMesh(torusKnot, options.updatable);
  20473. return torusKnot;
  20474. };
  20475. /**
  20476. * Creates a line system mesh.
  20477. * A line system is a pool of many lines gathered in a single mesh.
  20478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20479. * 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.
  20480. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20481. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20482. * 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
  20483. * 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
  20484. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20486. */
  20487. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20488. var instance = options.instance;
  20489. var lines = options.lines;
  20490. if (instance) {
  20491. var positionFunction = function (positions) {
  20492. var i = 0;
  20493. for (var l = 0; l < lines.length; l++) {
  20494. var points = lines[l];
  20495. for (var p = 0; p < points.length; p++) {
  20496. positions[i] = points[p].x;
  20497. positions[i + 1] = points[p].y;
  20498. positions[i + 2] = points[p].z;
  20499. i += 3;
  20500. }
  20501. }
  20502. };
  20503. instance.updateMeshPositions(positionFunction, false);
  20504. return instance;
  20505. }
  20506. // line system creation
  20507. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20508. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20509. vertexData.applyToMesh(lineSystem, options.updatable);
  20510. return lineSystem;
  20511. };
  20512. /**
  20513. * Creates a line mesh.
  20514. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20515. * 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.
  20516. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20517. * The parameter `points` is an array successive Vector3.
  20518. * 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
  20519. * When updating an instance, remember that only point positions can change, not the number of points.
  20520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20521. */
  20522. MeshBuilder.CreateLines = function (name, options, scene) {
  20523. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20524. return lines;
  20525. };
  20526. /**
  20527. * Creates a dashed line mesh.
  20528. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20529. * 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.
  20530. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20531. * The parameter `points` is an array successive Vector3.
  20532. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20533. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20534. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20535. * 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
  20536. * When updating an instance, remember that only point positions can change, not the number of points.
  20537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20538. */
  20539. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20540. var points = options.points;
  20541. var instance = options.instance;
  20542. var gapSize = options.gapSize;
  20543. var dashNb = options.dashNb;
  20544. var dashSize = options.dashSize;
  20545. if (instance) {
  20546. var positionFunction = function (positions) {
  20547. var curvect = BABYLON.Vector3.Zero();
  20548. var nbSeg = positions.length / 6;
  20549. var lg = 0;
  20550. var nb = 0;
  20551. var shft = 0;
  20552. var dashshft = 0;
  20553. var curshft = 0;
  20554. var p = 0;
  20555. var i = 0;
  20556. var j = 0;
  20557. for (i = 0; i < points.length - 1; i++) {
  20558. points[i + 1].subtractToRef(points[i], curvect);
  20559. lg += curvect.length();
  20560. }
  20561. shft = lg / nbSeg;
  20562. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20563. for (i = 0; i < points.length - 1; i++) {
  20564. points[i + 1].subtractToRef(points[i], curvect);
  20565. nb = Math.floor(curvect.length() / shft);
  20566. curvect.normalize();
  20567. j = 0;
  20568. while (j < nb && p < positions.length) {
  20569. curshft = shft * j;
  20570. positions[p] = points[i].x + curshft * curvect.x;
  20571. positions[p + 1] = points[i].y + curshft * curvect.y;
  20572. positions[p + 2] = points[i].z + curshft * curvect.z;
  20573. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20574. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20575. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20576. p += 6;
  20577. j++;
  20578. }
  20579. }
  20580. while (p < positions.length) {
  20581. positions[p] = points[i].x;
  20582. positions[p + 1] = points[i].y;
  20583. positions[p + 2] = points[i].z;
  20584. p += 3;
  20585. }
  20586. };
  20587. instance.updateMeshPositions(positionFunction, false);
  20588. return instance;
  20589. }
  20590. // dashed lines creation
  20591. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20592. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20593. vertexData.applyToMesh(dashedLines, options.updatable);
  20594. dashedLines.dashSize = dashSize;
  20595. dashedLines.gapSize = gapSize;
  20596. return dashedLines;
  20597. };
  20598. /**
  20599. * Creates an extruded shape mesh.
  20600. * 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.
  20601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20602. *
  20603. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20604. * 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
  20605. * extruded along the Z axis.
  20606. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20607. * 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.
  20608. * The parameter `scale` (float, default 1) is the value to scale the shape.
  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 optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20616. */
  20617. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20618. var path = options.path;
  20619. var shape = options.shape;
  20620. var scale = options.scale || 1;
  20621. var rotation = options.rotation || 0;
  20622. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20623. var updatable = options.updatable;
  20624. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20625. var instance = options.instance;
  20626. var invertUV = options.invertUV || false;
  20627. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20628. };
  20629. /**
  20630. * Creates an custom extruded shape mesh.
  20631. * 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.
  20632. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20633. *
  20634. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20635. * 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
  20636. * extruded along the Z axis.
  20637. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20638. * 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
  20639. * and the distance of this point from the begining of the path :
  20640. * ```javascript
  20641. * var rotationFunction = function(i, distance) {
  20642. * // do things
  20643. * return rotationValue; }
  20644. * ```
  20645. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20646. * 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
  20647. * and the distance of this point from the begining of the path :
  20648. * ```javascript
  20649. * var scaleFunction = function(i, distance) {
  20650. * // do things
  20651. * return scaleValue;}
  20652. * ```
  20653. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20654. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20655. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20656. * 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
  20657. * 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
  20658. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20661. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20663. */
  20664. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20665. var path = options.path;
  20666. var shape = options.shape;
  20667. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20668. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20669. var ribbonCloseArray = options.ribbonCloseArray || false;
  20670. var ribbonClosePath = options.ribbonClosePath || false;
  20671. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20672. var updatable = options.updatable;
  20673. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20674. var instance = options.instance;
  20675. var invertUV = options.invertUV || false;
  20676. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20677. };
  20678. /**
  20679. * Creates lathe mesh.
  20680. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20681. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20682. *
  20683. * 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
  20684. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20685. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20686. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20687. * 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.
  20688. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20689. * 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
  20690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20692. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20694. */
  20695. MeshBuilder.CreateLathe = function (name, options, scene) {
  20696. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20697. var closed = (options.closed === undefined) ? true : options.closed;
  20698. var shape = options.shape;
  20699. var radius = options.radius || 1;
  20700. var tessellation = options.tessellation || 64;
  20701. var updatable = options.updatable;
  20702. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20703. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20704. var pi2 = Math.PI * 2;
  20705. var paths = new Array();
  20706. var invertUV = options.invertUV || false;
  20707. var i = 0;
  20708. var p = 0;
  20709. var step = pi2 / tessellation * arc;
  20710. var rotated;
  20711. var path = new Array();
  20712. ;
  20713. for (i = 0; i <= tessellation; i++) {
  20714. var path = [];
  20715. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20716. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20717. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20718. }
  20719. for (p = 0; p < shape.length; p++) {
  20720. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20721. path.push(rotated);
  20722. }
  20723. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20724. 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));
  20725. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20726. }
  20727. paths.push(path);
  20728. }
  20729. // lathe ribbon
  20730. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20731. return lathe;
  20732. };
  20733. /**
  20734. * Creates a plane mesh.
  20735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20736. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20737. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20738. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20739. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20740. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20742. */
  20743. MeshBuilder.CreatePlane = function (name, options, scene) {
  20744. var plane = new BABYLON.Mesh(name, scene);
  20745. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20746. vertexData.applyToMesh(plane, options.updatable);
  20747. if (options.sourcePlane) {
  20748. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20749. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20750. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20751. plane.rotate(vectorProduct, product);
  20752. }
  20753. return plane;
  20754. };
  20755. /**
  20756. * Creates a ground mesh.
  20757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20758. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20759. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20761. */
  20762. MeshBuilder.CreateGround = function (name, options, scene) {
  20763. var ground = new BABYLON.GroundMesh(name, scene);
  20764. ground._setReady(false);
  20765. ground._subdivisions = options.subdivisions || 1;
  20766. ground._width = options.width || 1;
  20767. ground._height = options.height || 1;
  20768. ground._maxX = ground._width / 2;
  20769. ground._maxZ = ground._height / 2;
  20770. ground._minX = -ground._maxX;
  20771. ground._minZ = -ground._maxZ;
  20772. var vertexData = BABYLON.VertexData.CreateGround(options);
  20773. vertexData.applyToMesh(ground, options.updatable);
  20774. ground._setReady(true);
  20775. return ground;
  20776. };
  20777. /**
  20778. * Creates a tiled ground mesh.
  20779. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20780. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20781. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20782. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20783. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20784. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20785. * numbers of subdivisions on the ground width and height of each tile.
  20786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20787. */
  20788. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20789. var tiledGround = new BABYLON.Mesh(name, scene);
  20790. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20791. vertexData.applyToMesh(tiledGround, options.updatable);
  20792. return tiledGround;
  20793. };
  20794. /**
  20795. * Creates a ground mesh from a height map.
  20796. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20797. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20798. * The parameter `url` sets the URL of the height map image resource.
  20799. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20800. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20801. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20802. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20803. * 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).
  20804. * This function is passed the newly built mesh :
  20805. * ```javascript
  20806. * function(mesh) { // do things
  20807. * return; }
  20808. * ```
  20809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20810. */
  20811. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20812. var width = options.width || 10.0;
  20813. var height = options.height || 10.0;
  20814. var subdivisions = options.subdivisions || 1 | 0;
  20815. var minHeight = options.minHeight || 0.0;
  20816. var maxHeight = options.maxHeight || 10.0;
  20817. var updatable = options.updatable;
  20818. var onReady = options.onReady;
  20819. var ground = new BABYLON.GroundMesh(name, scene);
  20820. ground._subdivisions = subdivisions;
  20821. ground._width = width;
  20822. ground._height = height;
  20823. ground._maxX = ground._width / 2.0;
  20824. ground._maxZ = ground._height / 2.0;
  20825. ground._minX = -ground._maxX;
  20826. ground._minZ = -ground._maxZ;
  20827. ground._setReady(false);
  20828. var onload = function (img) {
  20829. // Getting height map data
  20830. var canvas = document.createElement("canvas");
  20831. var context = canvas.getContext("2d");
  20832. var bufferWidth = img.width;
  20833. var bufferHeight = img.height;
  20834. canvas.width = bufferWidth;
  20835. canvas.height = bufferHeight;
  20836. context.drawImage(img, 0, 0);
  20837. // Create VertexData from map data
  20838. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20839. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20840. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20841. width: width, height: height,
  20842. subdivisions: subdivisions,
  20843. minHeight: minHeight, maxHeight: maxHeight,
  20844. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20845. });
  20846. vertexData.applyToMesh(ground, updatable);
  20847. ground._setReady(true);
  20848. //execute ready callback, if set
  20849. if (onReady) {
  20850. onReady(ground);
  20851. }
  20852. };
  20853. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20854. return ground;
  20855. };
  20856. /**
  20857. * Creates a tube mesh.
  20858. * 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.
  20859. *
  20860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20861. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20862. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20863. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20864. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20865. * 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.
  20866. * It must return a radius value (positive float) :
  20867. * ```javascript
  20868. * var radiusFunction = function(i, distance) {
  20869. * // do things
  20870. * return radius; }
  20871. * ```
  20872. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20873. * 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
  20874. * 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
  20875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20877. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20879. */
  20880. MeshBuilder.CreateTube = function (name, options, scene) {
  20881. var path = options.path;
  20882. var radius = options.radius || 1.0;
  20883. var tessellation = options.tessellation || 64 | 0;
  20884. var radiusFunction = options.radiusFunction;
  20885. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20886. var invertUV = options.invertUV || false;
  20887. var updatable = options.updatable;
  20888. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20889. var instance = options.instance;
  20890. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  20891. // tube geometry
  20892. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20893. var tangents = path3D.getTangents();
  20894. var normals = path3D.getNormals();
  20895. var distances = path3D.getDistances();
  20896. var pi2 = Math.PI * 2;
  20897. var step = pi2 / tessellation * arc;
  20898. var returnRadius = function () { return radius; };
  20899. var radiusFunctionFinal = radiusFunction || returnRadius;
  20900. var circlePath;
  20901. var rad;
  20902. var normal;
  20903. var rotated;
  20904. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20905. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20906. for (var i = 0; i < path.length; i++) {
  20907. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20908. circlePath = Array(); // current circle array
  20909. normal = normals[i]; // current normal
  20910. for (var t = 0; t < tessellation; t++) {
  20911. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20912. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20913. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20914. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20915. circlePath[t] = rotated;
  20916. }
  20917. circlePaths[index] = circlePath;
  20918. index++;
  20919. }
  20920. // cap
  20921. var capPath = function (nbPoints, pathIndex) {
  20922. var pointCap = Array();
  20923. for (var i = 0; i < nbPoints; i++) {
  20924. pointCap.push(path[pathIndex]);
  20925. }
  20926. return pointCap;
  20927. };
  20928. switch (cap) {
  20929. case BABYLON.Mesh.NO_CAP:
  20930. break;
  20931. case BABYLON.Mesh.CAP_START:
  20932. circlePaths[0] = capPath(tessellation, 0);
  20933. circlePaths[1] = circlePaths[2].slice(0);
  20934. break;
  20935. case BABYLON.Mesh.CAP_END:
  20936. circlePaths[index] = circlePaths[index - 1].slice(0);
  20937. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20938. break;
  20939. case BABYLON.Mesh.CAP_ALL:
  20940. circlePaths[0] = capPath(tessellation, 0);
  20941. circlePaths[1] = circlePaths[2].slice(0);
  20942. circlePaths[index] = circlePaths[index - 1].slice(0);
  20943. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20944. break;
  20945. default:
  20946. break;
  20947. }
  20948. return circlePaths;
  20949. };
  20950. var path3D;
  20951. var pathArray;
  20952. if (instance) {
  20953. var arc = options.arc || instance.arc;
  20954. path3D = (instance.path3D).update(path);
  20955. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20956. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20957. instance.path3D = path3D;
  20958. instance.pathArray = pathArray;
  20959. instance.arc = arc;
  20960. return instance;
  20961. }
  20962. // tube creation
  20963. path3D = new BABYLON.Path3D(path);
  20964. var newPathArray = new Array();
  20965. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20966. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20967. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  20968. tube.pathArray = pathArray;
  20969. tube.path3D = path3D;
  20970. tube.tessellation = tessellation;
  20971. tube.cap = cap;
  20972. tube.arc = options.arc;
  20973. return tube;
  20974. };
  20975. /**
  20976. * Creates a polyhedron mesh.
  20977. *
  20978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20979. * 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
  20980. * to choose the wanted type.
  20981. * The parameter `size` (positive float, default 1) sets the polygon size.
  20982. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20983. * 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`.
  20984. * 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
  20985. * 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)`).
  20986. * 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
  20987. * 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.
  20988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20991. */
  20992. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20993. var polyhedron = new BABYLON.Mesh(name, scene);
  20994. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20995. vertexData.applyToMesh(polyhedron, options.updatable);
  20996. return polyhedron;
  20997. };
  20998. /**
  20999. * Creates a decal mesh.
  21000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21001. * 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.
  21002. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21003. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21004. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21005. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21006. */
  21007. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21008. var indices = sourceMesh.getIndices();
  21009. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21010. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21011. var position = options.position || BABYLON.Vector3.Zero();
  21012. var normal = options.normal || BABYLON.Vector3.Up();
  21013. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21014. var angle = options.angle || 0;
  21015. // Getting correct rotation
  21016. if (!normal) {
  21017. var target = new BABYLON.Vector3(0, 0, 1);
  21018. var camera = sourceMesh.getScene().activeCamera;
  21019. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21020. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21021. }
  21022. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21023. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21024. var pitch = Math.atan2(normal.y, len);
  21025. // Matrix
  21026. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21027. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21028. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21029. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21030. var vertexData = new BABYLON.VertexData();
  21031. vertexData.indices = [];
  21032. vertexData.positions = [];
  21033. vertexData.normals = [];
  21034. vertexData.uvs = [];
  21035. var currentVertexDataIndex = 0;
  21036. var extractDecalVector3 = function (indexId) {
  21037. var vertexId = indices[indexId];
  21038. var result = new BABYLON.PositionNormalVertex();
  21039. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21040. // Send vector to decal local world
  21041. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21042. // Get normal
  21043. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21044. return result;
  21045. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21046. var clip = function (vertices, axis) {
  21047. if (vertices.length === 0) {
  21048. return vertices;
  21049. }
  21050. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21051. var clipVertices = function (v0, v1) {
  21052. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21053. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21054. };
  21055. var result = new Array();
  21056. for (var index = 0; index < vertices.length; index += 3) {
  21057. var v1Out;
  21058. var v2Out;
  21059. var v3Out;
  21060. var total = 0;
  21061. var nV1, nV2, nV3, nV4;
  21062. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21063. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21064. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21065. v1Out = d1 > 0;
  21066. v2Out = d2 > 0;
  21067. v3Out = d3 > 0;
  21068. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21069. switch (total) {
  21070. case 0:
  21071. result.push(vertices[index]);
  21072. result.push(vertices[index + 1]);
  21073. result.push(vertices[index + 2]);
  21074. break;
  21075. case 1:
  21076. if (v1Out) {
  21077. nV1 = vertices[index + 1];
  21078. nV2 = vertices[index + 2];
  21079. nV3 = clipVertices(vertices[index], nV1);
  21080. nV4 = clipVertices(vertices[index], nV2);
  21081. }
  21082. if (v2Out) {
  21083. nV1 = vertices[index];
  21084. nV2 = vertices[index + 2];
  21085. nV3 = clipVertices(vertices[index + 1], nV1);
  21086. nV4 = clipVertices(vertices[index + 1], nV2);
  21087. result.push(nV3);
  21088. result.push(nV2.clone());
  21089. result.push(nV1.clone());
  21090. result.push(nV2.clone());
  21091. result.push(nV3.clone());
  21092. result.push(nV4);
  21093. break;
  21094. }
  21095. if (v3Out) {
  21096. nV1 = vertices[index];
  21097. nV2 = vertices[index + 1];
  21098. nV3 = clipVertices(vertices[index + 2], nV1);
  21099. nV4 = clipVertices(vertices[index + 2], nV2);
  21100. }
  21101. result.push(nV1.clone());
  21102. result.push(nV2.clone());
  21103. result.push(nV3);
  21104. result.push(nV4);
  21105. result.push(nV3.clone());
  21106. result.push(nV2.clone());
  21107. break;
  21108. case 2:
  21109. if (!v1Out) {
  21110. nV1 = vertices[index].clone();
  21111. nV2 = clipVertices(nV1, vertices[index + 1]);
  21112. nV3 = clipVertices(nV1, vertices[index + 2]);
  21113. result.push(nV1);
  21114. result.push(nV2);
  21115. result.push(nV3);
  21116. }
  21117. if (!v2Out) {
  21118. nV1 = vertices[index + 1].clone();
  21119. nV2 = clipVertices(nV1, vertices[index + 2]);
  21120. nV3 = clipVertices(nV1, vertices[index]);
  21121. result.push(nV1);
  21122. result.push(nV2);
  21123. result.push(nV3);
  21124. }
  21125. if (!v3Out) {
  21126. nV1 = vertices[index + 2].clone();
  21127. nV2 = clipVertices(nV1, vertices[index]);
  21128. nV3 = clipVertices(nV1, vertices[index + 1]);
  21129. result.push(nV1);
  21130. result.push(nV2);
  21131. result.push(nV3);
  21132. }
  21133. break;
  21134. case 3:
  21135. break;
  21136. }
  21137. }
  21138. return result;
  21139. };
  21140. for (var index = 0; index < indices.length; index += 3) {
  21141. var faceVertices = new Array();
  21142. faceVertices.push(extractDecalVector3(index));
  21143. faceVertices.push(extractDecalVector3(index + 1));
  21144. faceVertices.push(extractDecalVector3(index + 2));
  21145. // Clip
  21146. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21147. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21148. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21149. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21150. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21151. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21152. if (faceVertices.length === 0) {
  21153. continue;
  21154. }
  21155. // Add UVs and get back to world
  21156. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21157. var vertex = faceVertices[vIndex];
  21158. //TODO check for Int32Array
  21159. vertexData.indices.push(currentVertexDataIndex);
  21160. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21161. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21162. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21163. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21164. currentVertexDataIndex++;
  21165. }
  21166. }
  21167. // Return mesh
  21168. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21169. vertexData.applyToMesh(decal);
  21170. decal.position = position.clone();
  21171. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21172. return decal;
  21173. };
  21174. // Privates
  21175. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21176. // extrusion geometry
  21177. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21178. var tangents = path3D.getTangents();
  21179. var normals = path3D.getNormals();
  21180. var binormals = path3D.getBinormals();
  21181. var distances = path3D.getDistances();
  21182. var angle = 0;
  21183. var returnScale = function () { return scale; };
  21184. var returnRotation = function () { return rotation; };
  21185. var rotate = custom ? rotateFunction : returnRotation;
  21186. var scl = custom ? scaleFunction : returnScale;
  21187. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21188. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21189. for (var i = 0; i < curve.length; i++) {
  21190. var shapePath = new Array();
  21191. var angleStep = rotate(i, distances[i]);
  21192. var scaleRatio = scl(i, distances[i]);
  21193. for (var p = 0; p < shape.length; p++) {
  21194. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21195. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21196. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21197. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21198. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21199. shapePath[p] = rotated;
  21200. }
  21201. shapePaths[index] = shapePath;
  21202. angle += angleStep;
  21203. index++;
  21204. }
  21205. // cap
  21206. var capPath = function (shapePath) {
  21207. var pointCap = Array();
  21208. var barycenter = BABYLON.Vector3.Zero();
  21209. var i;
  21210. for (i = 0; i < shapePath.length; i++) {
  21211. barycenter.addInPlace(shapePath[i]);
  21212. }
  21213. barycenter.scaleInPlace(1 / shapePath.length);
  21214. for (i = 0; i < shapePath.length; i++) {
  21215. pointCap.push(barycenter);
  21216. }
  21217. return pointCap;
  21218. };
  21219. switch (cap) {
  21220. case BABYLON.Mesh.NO_CAP:
  21221. break;
  21222. case BABYLON.Mesh.CAP_START:
  21223. shapePaths[0] = capPath(shapePaths[2]);
  21224. shapePaths[1] = shapePaths[2].slice(0);
  21225. break;
  21226. case BABYLON.Mesh.CAP_END:
  21227. shapePaths[index] = shapePaths[index - 1];
  21228. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21229. break;
  21230. case BABYLON.Mesh.CAP_ALL:
  21231. shapePaths[0] = capPath(shapePaths[2]);
  21232. shapePaths[1] = shapePaths[2].slice(0);
  21233. shapePaths[index] = shapePaths[index - 1];
  21234. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21235. break;
  21236. default:
  21237. break;
  21238. }
  21239. return shapePaths;
  21240. };
  21241. var path3D;
  21242. var pathArray;
  21243. if (instance) {
  21244. path3D = (instance.path3D).update(curve);
  21245. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21246. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21247. return instance;
  21248. }
  21249. // extruded shape creation
  21250. path3D = new BABYLON.Path3D(curve);
  21251. var newShapePaths = new Array();
  21252. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21253. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21254. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21255. extrudedGeneric.pathArray = pathArray;
  21256. extrudedGeneric.path3D = path3D;
  21257. extrudedGeneric.cap = cap;
  21258. return extrudedGeneric;
  21259. };
  21260. return MeshBuilder;
  21261. })();
  21262. BABYLON.MeshBuilder = MeshBuilder;
  21263. })(BABYLON || (BABYLON = {}));
  21264. var BABYLON;
  21265. (function (BABYLON) {
  21266. var BaseTexture = (function () {
  21267. function BaseTexture(scene) {
  21268. this.hasAlpha = false;
  21269. this.getAlphaFromRGB = false;
  21270. this.level = 1;
  21271. this.coordinatesIndex = 0;
  21272. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21273. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21274. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21275. this.anisotropicFilteringLevel = 4;
  21276. this.isCube = false;
  21277. this.isRenderTarget = false;
  21278. this.animations = new Array();
  21279. /**
  21280. * An event triggered when the texture is disposed.
  21281. * @type {BABYLON.Observable}
  21282. */
  21283. this.onDisposeObservable = new BABYLON.Observable();
  21284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21285. this._scene = scene;
  21286. this._scene.textures.push(this);
  21287. }
  21288. BaseTexture.prototype.toString = function () {
  21289. return this.name;
  21290. };
  21291. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21292. set: function (callback) {
  21293. if (this._onDisposeObserver) {
  21294. this.onDisposeObservable.remove(this._onDisposeObserver);
  21295. }
  21296. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21297. },
  21298. enumerable: true,
  21299. configurable: true
  21300. });
  21301. BaseTexture.prototype.getScene = function () {
  21302. return this._scene;
  21303. };
  21304. BaseTexture.prototype.getTextureMatrix = function () {
  21305. return null;
  21306. };
  21307. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21308. return null;
  21309. };
  21310. BaseTexture.prototype.getInternalTexture = function () {
  21311. return this._texture;
  21312. };
  21313. BaseTexture.prototype.isReady = function () {
  21314. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21315. return true;
  21316. }
  21317. if (this._texture) {
  21318. return this._texture.isReady;
  21319. }
  21320. return false;
  21321. };
  21322. BaseTexture.prototype.getSize = function () {
  21323. if (this._texture._width) {
  21324. return { width: this._texture._width, height: this._texture._height };
  21325. }
  21326. if (this._texture._size) {
  21327. return { width: this._texture._size, height: this._texture._size };
  21328. }
  21329. return { width: 0, height: 0 };
  21330. };
  21331. BaseTexture.prototype.getBaseSize = function () {
  21332. if (!this.isReady() || !this._texture)
  21333. return { width: 0, height: 0 };
  21334. if (this._texture._size) {
  21335. return { width: this._texture._size, height: this._texture._size };
  21336. }
  21337. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  21338. };
  21339. BaseTexture.prototype.scale = function (ratio) {
  21340. };
  21341. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21342. get: function () {
  21343. return false;
  21344. },
  21345. enumerable: true,
  21346. configurable: true
  21347. });
  21348. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21349. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21350. for (var index = 0; index < texturesCache.length; index++) {
  21351. var texturesCacheEntry = texturesCache[index];
  21352. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21353. texturesCache.splice(index, 1);
  21354. return;
  21355. }
  21356. }
  21357. };
  21358. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21359. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21360. for (var index = 0; index < texturesCache.length; index++) {
  21361. var texturesCacheEntry = texturesCache[index];
  21362. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21363. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21364. texturesCacheEntry.references++;
  21365. return texturesCacheEntry;
  21366. }
  21367. }
  21368. }
  21369. return null;
  21370. };
  21371. BaseTexture.prototype.delayLoad = function () {
  21372. };
  21373. BaseTexture.prototype.clone = function () {
  21374. return null;
  21375. };
  21376. BaseTexture.prototype.releaseInternalTexture = function () {
  21377. if (this._texture) {
  21378. this._scene.getEngine().releaseInternalTexture(this._texture);
  21379. delete this._texture;
  21380. }
  21381. };
  21382. BaseTexture.prototype.dispose = function () {
  21383. // Animations
  21384. this.getScene().stopAnimation(this);
  21385. // Remove from scene
  21386. var index = this._scene.textures.indexOf(this);
  21387. if (index >= 0) {
  21388. this._scene.textures.splice(index, 1);
  21389. }
  21390. if (this._texture === undefined) {
  21391. return;
  21392. }
  21393. // Release
  21394. this.releaseInternalTexture();
  21395. // Callback
  21396. this.onDisposeObservable.notifyObservers(this);
  21397. this.onDisposeObservable.clear();
  21398. };
  21399. BaseTexture.prototype.serialize = function () {
  21400. if (!this.name) {
  21401. return null;
  21402. }
  21403. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21404. // Animations
  21405. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21406. return serializationObject;
  21407. };
  21408. __decorate([
  21409. BABYLON.serialize()
  21410. ], BaseTexture.prototype, "name", void 0);
  21411. __decorate([
  21412. BABYLON.serialize()
  21413. ], BaseTexture.prototype, "hasAlpha", void 0);
  21414. __decorate([
  21415. BABYLON.serialize()
  21416. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21417. __decorate([
  21418. BABYLON.serialize()
  21419. ], BaseTexture.prototype, "level", void 0);
  21420. __decorate([
  21421. BABYLON.serialize()
  21422. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21423. __decorate([
  21424. BABYLON.serialize()
  21425. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21426. __decorate([
  21427. BABYLON.serialize()
  21428. ], BaseTexture.prototype, "wrapU", void 0);
  21429. __decorate([
  21430. BABYLON.serialize()
  21431. ], BaseTexture.prototype, "wrapV", void 0);
  21432. __decorate([
  21433. BABYLON.serialize()
  21434. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21435. __decorate([
  21436. BABYLON.serialize()
  21437. ], BaseTexture.prototype, "isCube", void 0);
  21438. __decorate([
  21439. BABYLON.serialize()
  21440. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21441. return BaseTexture;
  21442. })();
  21443. BABYLON.BaseTexture = BaseTexture;
  21444. })(BABYLON || (BABYLON = {}));
  21445. var BABYLON;
  21446. (function (BABYLON) {
  21447. var Texture = (function (_super) {
  21448. __extends(Texture, _super);
  21449. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21450. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21451. if (onLoad === void 0) { onLoad = null; }
  21452. if (onError === void 0) { onError = null; }
  21453. if (buffer === void 0) { buffer = null; }
  21454. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21455. _super.call(this, scene);
  21456. this.uOffset = 0;
  21457. this.vOffset = 0;
  21458. this.uScale = 1.0;
  21459. this.vScale = 1.0;
  21460. this.uAng = 0;
  21461. this.vAng = 0;
  21462. this.wAng = 0;
  21463. this.name = url;
  21464. this.url = url;
  21465. this._noMipmap = noMipmap;
  21466. this._invertY = invertY;
  21467. this._samplingMode = samplingMode;
  21468. this._buffer = buffer;
  21469. this._deleteBuffer = deleteBuffer;
  21470. if (!url) {
  21471. return;
  21472. }
  21473. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21474. if (!this._texture) {
  21475. if (!scene.useDelayedTextureLoading) {
  21476. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  21477. if (deleteBuffer) {
  21478. delete this._buffer;
  21479. }
  21480. }
  21481. else {
  21482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21483. this._delayedOnLoad = onLoad;
  21484. this._delayedOnError = onError;
  21485. }
  21486. }
  21487. else {
  21488. BABYLON.Tools.SetImmediate(function () {
  21489. if (onLoad) {
  21490. onLoad();
  21491. }
  21492. });
  21493. }
  21494. }
  21495. Object.defineProperty(Texture.prototype, "noMipmap", {
  21496. get: function () {
  21497. return this._noMipmap;
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Texture.prototype.delayLoad = function () {
  21503. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21504. return;
  21505. }
  21506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21507. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21508. if (!this._texture) {
  21509. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21510. if (this._deleteBuffer) {
  21511. delete this._buffer;
  21512. }
  21513. }
  21514. };
  21515. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21516. if (!this._texture) {
  21517. return;
  21518. }
  21519. this._samplingMode = samplingMode;
  21520. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21521. };
  21522. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21523. x *= this.uScale;
  21524. y *= this.vScale;
  21525. x -= 0.5 * this.uScale;
  21526. y -= 0.5 * this.vScale;
  21527. z -= 0.5;
  21528. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21529. t.x += 0.5 * this.uScale + this.uOffset;
  21530. t.y += 0.5 * this.vScale + this.vOffset;
  21531. t.z += 0.5;
  21532. };
  21533. Texture.prototype.getTextureMatrix = function () {
  21534. if (this.uOffset === this._cachedUOffset &&
  21535. this.vOffset === this._cachedVOffset &&
  21536. this.uScale === this._cachedUScale &&
  21537. this.vScale === this._cachedVScale &&
  21538. this.uAng === this._cachedUAng &&
  21539. this.vAng === this._cachedVAng &&
  21540. this.wAng === this._cachedWAng) {
  21541. return this._cachedTextureMatrix;
  21542. }
  21543. this._cachedUOffset = this.uOffset;
  21544. this._cachedVOffset = this.vOffset;
  21545. this._cachedUScale = this.uScale;
  21546. this._cachedVScale = this.vScale;
  21547. this._cachedUAng = this.uAng;
  21548. this._cachedVAng = this.vAng;
  21549. this._cachedWAng = this.wAng;
  21550. if (!this._cachedTextureMatrix) {
  21551. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21552. this._rowGenerationMatrix = new BABYLON.Matrix();
  21553. this._t0 = BABYLON.Vector3.Zero();
  21554. this._t1 = BABYLON.Vector3.Zero();
  21555. this._t2 = BABYLON.Vector3.Zero();
  21556. }
  21557. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21558. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21559. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21560. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21561. this._t1.subtractInPlace(this._t0);
  21562. this._t2.subtractInPlace(this._t0);
  21563. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21564. this._cachedTextureMatrix.m[0] = this._t1.x;
  21565. this._cachedTextureMatrix.m[1] = this._t1.y;
  21566. this._cachedTextureMatrix.m[2] = this._t1.z;
  21567. this._cachedTextureMatrix.m[4] = this._t2.x;
  21568. this._cachedTextureMatrix.m[5] = this._t2.y;
  21569. this._cachedTextureMatrix.m[6] = this._t2.z;
  21570. this._cachedTextureMatrix.m[8] = this._t0.x;
  21571. this._cachedTextureMatrix.m[9] = this._t0.y;
  21572. this._cachedTextureMatrix.m[10] = this._t0.z;
  21573. return this._cachedTextureMatrix;
  21574. };
  21575. Texture.prototype.getReflectionTextureMatrix = function () {
  21576. if (this.uOffset === this._cachedUOffset &&
  21577. this.vOffset === this._cachedVOffset &&
  21578. this.uScale === this._cachedUScale &&
  21579. this.vScale === this._cachedVScale &&
  21580. this.coordinatesMode === this._cachedCoordinatesMode) {
  21581. return this._cachedTextureMatrix;
  21582. }
  21583. if (!this._cachedTextureMatrix) {
  21584. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21585. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21586. }
  21587. this._cachedCoordinatesMode = this.coordinatesMode;
  21588. switch (this.coordinatesMode) {
  21589. case Texture.PLANAR_MODE:
  21590. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21591. this._cachedTextureMatrix[0] = this.uScale;
  21592. this._cachedTextureMatrix[5] = this.vScale;
  21593. this._cachedTextureMatrix[12] = this.uOffset;
  21594. this._cachedTextureMatrix[13] = this.vOffset;
  21595. break;
  21596. case Texture.PROJECTION_MODE:
  21597. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21598. this._projectionModeMatrix.m[0] = 0.5;
  21599. this._projectionModeMatrix.m[5] = -0.5;
  21600. this._projectionModeMatrix.m[10] = 0.0;
  21601. this._projectionModeMatrix.m[12] = 0.5;
  21602. this._projectionModeMatrix.m[13] = 0.5;
  21603. this._projectionModeMatrix.m[14] = 1.0;
  21604. this._projectionModeMatrix.m[15] = 1.0;
  21605. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21606. break;
  21607. default:
  21608. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21609. break;
  21610. }
  21611. return this._cachedTextureMatrix;
  21612. };
  21613. Texture.prototype.clone = function () {
  21614. var _this = this;
  21615. return BABYLON.SerializationHelper.Clone(function () {
  21616. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21617. }, this);
  21618. };
  21619. // Statics
  21620. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21621. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21622. if (onLoad === void 0) { onLoad = null; }
  21623. if (onError === void 0) { onError = null; }
  21624. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21625. };
  21626. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21627. if (parsedTexture.isCube) {
  21628. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21629. }
  21630. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21631. return null;
  21632. }
  21633. var texture = BABYLON.SerializationHelper.Parse(function () {
  21634. if (parsedTexture.mirrorPlane) {
  21635. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21636. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21637. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21638. return mirrorTexture;
  21639. }
  21640. else if (parsedTexture.isRenderTarget) {
  21641. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21642. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21643. return renderTargetTexture;
  21644. }
  21645. else {
  21646. var texture;
  21647. if (parsedTexture.base64String) {
  21648. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21649. }
  21650. else {
  21651. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21652. }
  21653. return texture;
  21654. }
  21655. }, parsedTexture, scene);
  21656. // Animations
  21657. if (parsedTexture.animations) {
  21658. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21659. var parsedAnimation = parsedTexture.animations[animationIndex];
  21660. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21661. }
  21662. }
  21663. return texture;
  21664. };
  21665. // Constants
  21666. Texture.NEAREST_SAMPLINGMODE = 1;
  21667. Texture.BILINEAR_SAMPLINGMODE = 2;
  21668. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21669. Texture.EXPLICIT_MODE = 0;
  21670. Texture.SPHERICAL_MODE = 1;
  21671. Texture.PLANAR_MODE = 2;
  21672. Texture.CUBIC_MODE = 3;
  21673. Texture.PROJECTION_MODE = 4;
  21674. Texture.SKYBOX_MODE = 5;
  21675. Texture.INVCUBIC_MODE = 6;
  21676. Texture.EQUIRECTANGULAR_MODE = 7;
  21677. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21678. Texture.CLAMP_ADDRESSMODE = 0;
  21679. Texture.WRAP_ADDRESSMODE = 1;
  21680. Texture.MIRROR_ADDRESSMODE = 2;
  21681. __decorate([
  21682. BABYLON.serialize()
  21683. ], Texture.prototype, "url", void 0);
  21684. __decorate([
  21685. BABYLON.serialize()
  21686. ], Texture.prototype, "uOffset", void 0);
  21687. __decorate([
  21688. BABYLON.serialize()
  21689. ], Texture.prototype, "vOffset", void 0);
  21690. __decorate([
  21691. BABYLON.serialize()
  21692. ], Texture.prototype, "uScale", void 0);
  21693. __decorate([
  21694. BABYLON.serialize()
  21695. ], Texture.prototype, "vScale", void 0);
  21696. __decorate([
  21697. BABYLON.serialize()
  21698. ], Texture.prototype, "uAng", void 0);
  21699. __decorate([
  21700. BABYLON.serialize()
  21701. ], Texture.prototype, "vAng", void 0);
  21702. __decorate([
  21703. BABYLON.serialize()
  21704. ], Texture.prototype, "wAng", void 0);
  21705. return Texture;
  21706. })(BABYLON.BaseTexture);
  21707. BABYLON.Texture = Texture;
  21708. })(BABYLON || (BABYLON = {}));
  21709. var BABYLON;
  21710. (function (BABYLON) {
  21711. var CubeTexture = (function (_super) {
  21712. __extends(CubeTexture, _super);
  21713. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21714. _super.call(this, scene);
  21715. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21716. this.name = rootUrl;
  21717. this.url = rootUrl;
  21718. this._noMipmap = noMipmap;
  21719. this.hasAlpha = false;
  21720. if (!rootUrl && !files) {
  21721. return;
  21722. }
  21723. this._texture = this._getFromCache(rootUrl, noMipmap);
  21724. if (!files) {
  21725. if (!extensions) {
  21726. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21727. }
  21728. files = [];
  21729. for (var index = 0; index < extensions.length; index++) {
  21730. files.push(rootUrl + extensions[index]);
  21731. }
  21732. this._extensions = extensions;
  21733. }
  21734. this._files = files;
  21735. if (!this._texture) {
  21736. if (!scene.useDelayedTextureLoading) {
  21737. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21738. }
  21739. else {
  21740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21741. }
  21742. }
  21743. this.isCube = true;
  21744. this._textureMatrix = BABYLON.Matrix.Identity();
  21745. }
  21746. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21747. return new CubeTexture("", scene, null, noMipmap, files);
  21748. };
  21749. // Methods
  21750. CubeTexture.prototype.delayLoad = function () {
  21751. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21752. return;
  21753. }
  21754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21755. this._texture = this._getFromCache(this.url, this._noMipmap);
  21756. if (!this._texture) {
  21757. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  21758. }
  21759. };
  21760. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21761. return this._textureMatrix;
  21762. };
  21763. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21764. var texture = BABYLON.SerializationHelper.Parse(function () {
  21765. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21766. }, parsedTexture, scene);
  21767. // Animations
  21768. if (parsedTexture.animations) {
  21769. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21770. var parsedAnimation = parsedTexture.animations[animationIndex];
  21771. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21772. }
  21773. }
  21774. return texture;
  21775. };
  21776. CubeTexture.prototype.clone = function () {
  21777. var _this = this;
  21778. return BABYLON.SerializationHelper.Clone(function () {
  21779. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21780. }, this);
  21781. };
  21782. return CubeTexture;
  21783. })(BABYLON.BaseTexture);
  21784. BABYLON.CubeTexture = CubeTexture;
  21785. })(BABYLON || (BABYLON = {}));
  21786. var BABYLON;
  21787. (function (BABYLON) {
  21788. var RenderTargetTexture = (function (_super) {
  21789. __extends(RenderTargetTexture, _super);
  21790. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21791. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21792. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21793. if (isCube === void 0) { isCube = false; }
  21794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21795. _super.call(this, null, scene, !generateMipMaps);
  21796. this.isCube = isCube;
  21797. /**
  21798. * Use this list to define the list of mesh you want to render.
  21799. */
  21800. this.renderList = new Array();
  21801. this.renderParticles = true;
  21802. this.renderSprites = false;
  21803. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21804. // Events
  21805. /**
  21806. * An event triggered when the texture is unbind.
  21807. * @type {BABYLON.Observable}
  21808. */
  21809. this.onAfterUnbindObservable = new BABYLON.Observable();
  21810. /**
  21811. * An event triggered before rendering the texture
  21812. * @type {BABYLON.Observable}
  21813. */
  21814. this.onBeforeRenderObservable = new BABYLON.Observable();
  21815. /**
  21816. * An event triggered after rendering the texture
  21817. * @type {BABYLON.Observable}
  21818. */
  21819. this.onAfterRenderObservable = new BABYLON.Observable();
  21820. /**
  21821. * An event triggered after the texture clear
  21822. * @type {BABYLON.Observable}
  21823. */
  21824. this.onClearObservable = new BABYLON.Observable();
  21825. this._currentRefreshId = -1;
  21826. this._refreshRate = 1;
  21827. this.name = name;
  21828. this.isRenderTarget = true;
  21829. this._size = size;
  21830. this._generateMipMaps = generateMipMaps;
  21831. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21832. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  21833. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21834. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21835. }
  21836. if (isCube) {
  21837. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  21838. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21839. this._textureMatrix = BABYLON.Matrix.Identity();
  21840. }
  21841. else {
  21842. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  21843. }
  21844. // Rendering groups
  21845. this._renderingManager = new BABYLON.RenderingManager(scene);
  21846. }
  21847. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21848. get: function () {
  21849. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21855. get: function () {
  21856. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21857. },
  21858. enumerable: true,
  21859. configurable: true
  21860. });
  21861. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21862. get: function () {
  21863. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21869. set: function (callback) {
  21870. if (this._onAfterUnbindObserver) {
  21871. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21872. }
  21873. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21874. },
  21875. enumerable: true,
  21876. configurable: true
  21877. });
  21878. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21879. set: function (callback) {
  21880. if (this._onBeforeRenderObserver) {
  21881. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21882. }
  21883. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21884. },
  21885. enumerable: true,
  21886. configurable: true
  21887. });
  21888. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21889. set: function (callback) {
  21890. if (this._onAfterRenderObserver) {
  21891. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21892. }
  21893. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21899. set: function (callback) {
  21900. if (this._onClearObserver) {
  21901. this.onClearObservable.remove(this._onClearObserver);
  21902. }
  21903. this._onClearObserver = this.onClearObservable.add(callback);
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21909. this._currentRefreshId = -1;
  21910. };
  21911. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21912. get: function () {
  21913. return this._refreshRate;
  21914. },
  21915. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21916. set: function (value) {
  21917. this._refreshRate = value;
  21918. this.resetRefreshCounter();
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. RenderTargetTexture.prototype._shouldRender = function () {
  21924. if (this._currentRefreshId === -1) {
  21925. this._currentRefreshId = 1;
  21926. return true;
  21927. }
  21928. if (this.refreshRate === this._currentRefreshId) {
  21929. this._currentRefreshId = 1;
  21930. return true;
  21931. }
  21932. this._currentRefreshId++;
  21933. return false;
  21934. };
  21935. RenderTargetTexture.prototype.isReady = function () {
  21936. if (!this.getScene().renderTargetsEnabled) {
  21937. return false;
  21938. }
  21939. return _super.prototype.isReady.call(this);
  21940. };
  21941. RenderTargetTexture.prototype.getRenderSize = function () {
  21942. return this._size;
  21943. };
  21944. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21945. get: function () {
  21946. return true;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. RenderTargetTexture.prototype.scale = function (ratio) {
  21952. var newSize = this._size * ratio;
  21953. this.resize(newSize, this._generateMipMaps);
  21954. };
  21955. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21956. if (this.isCube) {
  21957. return this._textureMatrix;
  21958. }
  21959. return _super.prototype.getReflectionTextureMatrix.call(this);
  21960. };
  21961. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21962. this.releaseInternalTexture();
  21963. if (this.isCube) {
  21964. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21965. }
  21966. else {
  21967. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21968. }
  21969. };
  21970. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21971. var scene = this.getScene();
  21972. if (this.useCameraPostProcesses !== undefined) {
  21973. useCameraPostProcess = this.useCameraPostProcesses;
  21974. }
  21975. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21976. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21977. }
  21978. if (this._waitingRenderList) {
  21979. this.renderList = [];
  21980. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21981. var id = this._waitingRenderList[index];
  21982. this.renderList.push(scene.getMeshByID(id));
  21983. }
  21984. delete this._waitingRenderList;
  21985. }
  21986. // Is predicate defined?
  21987. if (this.renderListPredicate) {
  21988. this.renderList.splice(0); // Clear previous renderList
  21989. var sceneMeshes = this.getScene().meshes;
  21990. for (var index = 0; index < sceneMeshes.length; index++) {
  21991. var mesh = sceneMeshes[index];
  21992. if (this.renderListPredicate(mesh)) {
  21993. this.renderList.push(mesh);
  21994. }
  21995. }
  21996. }
  21997. if (this.renderList && this.renderList.length === 0) {
  21998. return;
  21999. }
  22000. // Prepare renderingManager
  22001. this._renderingManager.reset();
  22002. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22003. var sceneRenderId = scene.getRenderId();
  22004. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  22005. var mesh = currentRenderList[meshIndex];
  22006. if (mesh) {
  22007. if (!mesh.isReady()) {
  22008. // Reset _currentRefreshId
  22009. this.resetRefreshCounter();
  22010. continue;
  22011. }
  22012. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22013. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22014. mesh._activate(sceneRenderId);
  22015. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22016. var subMesh = mesh.subMeshes[subIndex];
  22017. scene._activeIndices.addCount(subMesh.indexCount, false);
  22018. this._renderingManager.dispatch(subMesh);
  22019. }
  22020. }
  22021. }
  22022. }
  22023. if (this.isCube) {
  22024. for (var face = 0; face < 6; face++) {
  22025. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  22026. scene.incrementRenderId();
  22027. scene.resetCachedMaterial();
  22028. }
  22029. }
  22030. else {
  22031. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  22032. }
  22033. this.onAfterUnbindObservable.notifyObservers(this);
  22034. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22035. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22036. }
  22037. scene.resetCachedMaterial();
  22038. };
  22039. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  22040. var scene = this.getScene();
  22041. var engine = scene.getEngine();
  22042. // Bind
  22043. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22044. if (this.isCube) {
  22045. engine.bindFramebuffer(this._texture, faceIndex);
  22046. }
  22047. else {
  22048. engine.bindFramebuffer(this._texture);
  22049. }
  22050. }
  22051. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22052. // Clear
  22053. if (this.onClearObservable.hasObservers()) {
  22054. this.onClearObservable.notifyObservers(engine);
  22055. }
  22056. else {
  22057. engine.clear(scene.clearColor, true, true);
  22058. }
  22059. if (!this._doNotChangeAspectRatio) {
  22060. scene.updateTransformMatrix(true);
  22061. }
  22062. // Render
  22063. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22064. if (useCameraPostProcess) {
  22065. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22066. }
  22067. if (!this._doNotChangeAspectRatio) {
  22068. scene.updateTransformMatrix(true);
  22069. }
  22070. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22071. // Dump ?
  22072. if (dumpForDebug) {
  22073. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22074. }
  22075. // Unbind
  22076. if (!this.isCube || faceIndex === 5) {
  22077. if (this.isCube) {
  22078. if (faceIndex === 5) {
  22079. engine.generateMipMapsForCubemap(this._texture);
  22080. }
  22081. }
  22082. engine.unBindFramebuffer(this._texture, this.isCube);
  22083. }
  22084. };
  22085. RenderTargetTexture.prototype.clone = function () {
  22086. var textureSize = this.getSize();
  22087. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22088. // Base texture
  22089. newTexture.hasAlpha = this.hasAlpha;
  22090. newTexture.level = this.level;
  22091. // RenderTarget Texture
  22092. newTexture.coordinatesMode = this.coordinatesMode;
  22093. newTexture.renderList = this.renderList.slice(0);
  22094. return newTexture;
  22095. };
  22096. RenderTargetTexture.prototype.serialize = function () {
  22097. if (!this.name) {
  22098. return null;
  22099. }
  22100. var serializationObject = _super.prototype.serialize.call(this);
  22101. serializationObject.renderTargetSize = this.getRenderSize();
  22102. serializationObject.renderList = [];
  22103. for (var index = 0; index < this.renderList.length; index++) {
  22104. serializationObject.renderList.push(this.renderList[index].id);
  22105. }
  22106. return serializationObject;
  22107. };
  22108. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22109. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22110. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22111. return RenderTargetTexture;
  22112. })(BABYLON.Texture);
  22113. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22114. })(BABYLON || (BABYLON = {}));
  22115. var BABYLON;
  22116. (function (BABYLON) {
  22117. var ProceduralTexture = (function (_super) {
  22118. __extends(ProceduralTexture, _super);
  22119. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22120. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22121. if (isCube === void 0) { isCube = false; }
  22122. _super.call(this, null, scene, !generateMipMaps);
  22123. this.isCube = isCube;
  22124. this.isEnabled = true;
  22125. this._currentRefreshId = -1;
  22126. this._refreshRate = 1;
  22127. this._vertexBuffers = {};
  22128. this._uniforms = new Array();
  22129. this._samplers = new Array();
  22130. this._textures = new Array();
  22131. this._floats = new Array();
  22132. this._floatsArrays = {};
  22133. this._colors3 = new Array();
  22134. this._colors4 = new Array();
  22135. this._vectors2 = new Array();
  22136. this._vectors3 = new Array();
  22137. this._matrices = new Array();
  22138. this._fallbackTextureUsed = false;
  22139. scene._proceduralTextures.push(this);
  22140. this.name = name;
  22141. this.isRenderTarget = true;
  22142. this._size = size;
  22143. this._generateMipMaps = generateMipMaps;
  22144. this.setFragment(fragment);
  22145. this._fallbackTexture = fallbackTexture;
  22146. var engine = scene.getEngine();
  22147. if (isCube) {
  22148. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22149. this.setFloat("face", 0);
  22150. }
  22151. else {
  22152. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22153. }
  22154. // VBO
  22155. var vertices = [];
  22156. vertices.push(1, 1);
  22157. vertices.push(-1, 1);
  22158. vertices.push(-1, -1);
  22159. vertices.push(1, -1);
  22160. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22161. // Indices
  22162. var indices = [];
  22163. indices.push(0);
  22164. indices.push(1);
  22165. indices.push(2);
  22166. indices.push(0);
  22167. indices.push(2);
  22168. indices.push(3);
  22169. this._indexBuffer = engine.createIndexBuffer(indices);
  22170. }
  22171. ProceduralTexture.prototype.reset = function () {
  22172. if (this._effect === undefined) {
  22173. return;
  22174. }
  22175. var engine = this.getScene().getEngine();
  22176. engine._releaseEffect(this._effect);
  22177. };
  22178. ProceduralTexture.prototype.isReady = function () {
  22179. var _this = this;
  22180. var engine = this.getScene().getEngine();
  22181. var shaders;
  22182. if (!this._fragment) {
  22183. return false;
  22184. }
  22185. if (this._fallbackTextureUsed) {
  22186. return true;
  22187. }
  22188. if (this._fragment.fragmentElement !== undefined) {
  22189. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22190. }
  22191. else {
  22192. shaders = { vertex: "procedural", fragment: this._fragment };
  22193. }
  22194. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22195. _this.releaseInternalTexture();
  22196. if (_this._fallbackTexture) {
  22197. _this._texture = _this._fallbackTexture._texture;
  22198. _this._texture.references++;
  22199. }
  22200. _this._fallbackTextureUsed = true;
  22201. });
  22202. return this._effect.isReady();
  22203. };
  22204. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22205. this._currentRefreshId = -1;
  22206. };
  22207. ProceduralTexture.prototype.setFragment = function (fragment) {
  22208. this._fragment = fragment;
  22209. };
  22210. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22211. get: function () {
  22212. return this._refreshRate;
  22213. },
  22214. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22215. set: function (value) {
  22216. this._refreshRate = value;
  22217. this.resetRefreshCounter();
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. ProceduralTexture.prototype._shouldRender = function () {
  22223. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22224. return false;
  22225. }
  22226. if (this._fallbackTextureUsed) {
  22227. return false;
  22228. }
  22229. if (this._currentRefreshId === -1) {
  22230. this._currentRefreshId = 1;
  22231. return true;
  22232. }
  22233. if (this.refreshRate === this._currentRefreshId) {
  22234. this._currentRefreshId = 1;
  22235. return true;
  22236. }
  22237. this._currentRefreshId++;
  22238. return false;
  22239. };
  22240. ProceduralTexture.prototype.getRenderSize = function () {
  22241. return this._size;
  22242. };
  22243. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22244. if (this._fallbackTextureUsed) {
  22245. return;
  22246. }
  22247. this.releaseInternalTexture();
  22248. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22249. };
  22250. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22251. if (this._uniforms.indexOf(uniformName) === -1) {
  22252. this._uniforms.push(uniformName);
  22253. }
  22254. };
  22255. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22256. if (this._samplers.indexOf(name) === -1) {
  22257. this._samplers.push(name);
  22258. }
  22259. this._textures[name] = texture;
  22260. return this;
  22261. };
  22262. ProceduralTexture.prototype.setFloat = function (name, value) {
  22263. this._checkUniform(name);
  22264. this._floats[name] = value;
  22265. return this;
  22266. };
  22267. ProceduralTexture.prototype.setFloats = function (name, value) {
  22268. this._checkUniform(name);
  22269. this._floatsArrays[name] = value;
  22270. return this;
  22271. };
  22272. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22273. this._checkUniform(name);
  22274. this._colors3[name] = value;
  22275. return this;
  22276. };
  22277. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22278. this._checkUniform(name);
  22279. this._colors4[name] = value;
  22280. return this;
  22281. };
  22282. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22283. this._checkUniform(name);
  22284. this._vectors2[name] = value;
  22285. return this;
  22286. };
  22287. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22288. this._checkUniform(name);
  22289. this._vectors3[name] = value;
  22290. return this;
  22291. };
  22292. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22293. this._checkUniform(name);
  22294. this._matrices[name] = value;
  22295. return this;
  22296. };
  22297. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22298. var scene = this.getScene();
  22299. var engine = scene.getEngine();
  22300. // Render
  22301. engine.enableEffect(this._effect);
  22302. engine.setState(false);
  22303. // Texture
  22304. for (var name in this._textures) {
  22305. this._effect.setTexture(name, this._textures[name]);
  22306. }
  22307. // Float
  22308. for (name in this._floats) {
  22309. this._effect.setFloat(name, this._floats[name]);
  22310. }
  22311. // Floats
  22312. for (name in this._floatsArrays) {
  22313. this._effect.setArray(name, this._floatsArrays[name]);
  22314. }
  22315. // Color3
  22316. for (name in this._colors3) {
  22317. this._effect.setColor3(name, this._colors3[name]);
  22318. }
  22319. // Color4
  22320. for (name in this._colors4) {
  22321. var color = this._colors4[name];
  22322. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22323. }
  22324. // Vector2
  22325. for (name in this._vectors2) {
  22326. this._effect.setVector2(name, this._vectors2[name]);
  22327. }
  22328. // Vector3
  22329. for (name in this._vectors3) {
  22330. this._effect.setVector3(name, this._vectors3[name]);
  22331. }
  22332. // Matrix
  22333. for (name in this._matrices) {
  22334. this._effect.setMatrix(name, this._matrices[name]);
  22335. }
  22336. // VBOs
  22337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22338. if (this.isCube) {
  22339. for (var face = 0; face < 6; face++) {
  22340. engine.bindFramebuffer(this._texture, face);
  22341. this._effect.setFloat("face", face);
  22342. // Clear
  22343. engine.clear(scene.clearColor, true, true);
  22344. // Draw order
  22345. engine.draw(true, 0, 6);
  22346. // Mipmaps
  22347. if (face === 5) {
  22348. engine.generateMipMapsForCubemap(this._texture);
  22349. }
  22350. }
  22351. }
  22352. else {
  22353. engine.bindFramebuffer(this._texture);
  22354. // Clear
  22355. engine.clear(scene.clearColor, true, true);
  22356. // Draw order
  22357. engine.draw(true, 0, 6);
  22358. }
  22359. // Unbind
  22360. engine.unBindFramebuffer(this._texture, this.isCube);
  22361. if (this.onGenerated) {
  22362. this.onGenerated();
  22363. }
  22364. };
  22365. ProceduralTexture.prototype.clone = function () {
  22366. var textureSize = this.getSize();
  22367. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22368. // Base texture
  22369. newTexture.hasAlpha = this.hasAlpha;
  22370. newTexture.level = this.level;
  22371. // RenderTarget Texture
  22372. newTexture.coordinatesMode = this.coordinatesMode;
  22373. return newTexture;
  22374. };
  22375. ProceduralTexture.prototype.dispose = function () {
  22376. var index = this.getScene()._proceduralTextures.indexOf(this);
  22377. if (index >= 0) {
  22378. this.getScene()._proceduralTextures.splice(index, 1);
  22379. }
  22380. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22381. if (vertexBuffer) {
  22382. vertexBuffer.dispose();
  22383. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22384. }
  22385. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22386. this._indexBuffer = null;
  22387. }
  22388. _super.prototype.dispose.call(this);
  22389. };
  22390. return ProceduralTexture;
  22391. })(BABYLON.Texture);
  22392. BABYLON.ProceduralTexture = ProceduralTexture;
  22393. })(BABYLON || (BABYLON = {}));
  22394. var BABYLON;
  22395. (function (BABYLON) {
  22396. var MirrorTexture = (function (_super) {
  22397. __extends(MirrorTexture, _super);
  22398. function MirrorTexture(name, size, scene, generateMipMaps) {
  22399. var _this = this;
  22400. _super.call(this, name, size, scene, generateMipMaps, true);
  22401. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22402. this._transformMatrix = BABYLON.Matrix.Zero();
  22403. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22404. this.onBeforeRenderObservable.add(function () {
  22405. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22406. _this._savedViewMatrix = scene.getViewMatrix();
  22407. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22408. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22409. scene.clipPlane = _this.mirrorPlane;
  22410. scene.getEngine().cullBackFaces = false;
  22411. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22412. });
  22413. this.onAfterRenderObservable.add(function () {
  22414. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22415. scene.getEngine().cullBackFaces = true;
  22416. scene._mirroredCameraPosition = null;
  22417. delete scene.clipPlane;
  22418. });
  22419. }
  22420. MirrorTexture.prototype.clone = function () {
  22421. var textureSize = this.getSize();
  22422. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22423. // Base texture
  22424. newTexture.hasAlpha = this.hasAlpha;
  22425. newTexture.level = this.level;
  22426. // Mirror Texture
  22427. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22428. newTexture.renderList = this.renderList.slice(0);
  22429. return newTexture;
  22430. };
  22431. MirrorTexture.prototype.serialize = function () {
  22432. if (!this.name) {
  22433. return null;
  22434. }
  22435. var serializationObject = _super.prototype.serialize.call(this);
  22436. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22437. return serializationObject;
  22438. };
  22439. return MirrorTexture;
  22440. })(BABYLON.RenderTargetTexture);
  22441. BABYLON.MirrorTexture = MirrorTexture;
  22442. })(BABYLON || (BABYLON = {}));
  22443. var BABYLON;
  22444. (function (BABYLON) {
  22445. /**
  22446. * Creates a refraction texture used by refraction channel of the standard material.
  22447. * @param name the texture name
  22448. * @param size size of the underlying texture
  22449. * @param scene root scene
  22450. */
  22451. var RefractionTexture = (function (_super) {
  22452. __extends(RefractionTexture, _super);
  22453. function RefractionTexture(name, size, scene, generateMipMaps) {
  22454. var _this = this;
  22455. _super.call(this, name, size, scene, generateMipMaps, true);
  22456. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22457. this.depth = 2.0;
  22458. this.onBeforeRenderObservable.add(function () {
  22459. scene.clipPlane = _this.refractionPlane;
  22460. });
  22461. this.onAfterRenderObservable.add(function () {
  22462. delete scene.clipPlane;
  22463. });
  22464. }
  22465. RefractionTexture.prototype.clone = function () {
  22466. var textureSize = this.getSize();
  22467. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22468. // Base texture
  22469. newTexture.hasAlpha = this.hasAlpha;
  22470. newTexture.level = this.level;
  22471. // Refraction Texture
  22472. newTexture.refractionPlane = this.refractionPlane.clone();
  22473. newTexture.renderList = this.renderList.slice(0);
  22474. newTexture.depth = this.depth;
  22475. return newTexture;
  22476. };
  22477. RefractionTexture.prototype.serialize = function () {
  22478. if (!this.name) {
  22479. return null;
  22480. }
  22481. var serializationObject = _super.prototype.serialize.call(this);
  22482. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22483. serializationObject.depth = this.depth;
  22484. return serializationObject;
  22485. };
  22486. return RefractionTexture;
  22487. })(BABYLON.RenderTargetTexture);
  22488. BABYLON.RefractionTexture = RefractionTexture;
  22489. })(BABYLON || (BABYLON = {}));
  22490. var BABYLON;
  22491. (function (BABYLON) {
  22492. var DynamicTexture = (function (_super) {
  22493. __extends(DynamicTexture, _super);
  22494. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22496. _super.call(this, null, scene, !generateMipMaps);
  22497. this.name = name;
  22498. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22499. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22500. this._generateMipMaps = generateMipMaps;
  22501. if (options.getContext) {
  22502. this._canvas = options;
  22503. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22504. }
  22505. else {
  22506. this._canvas = document.createElement("canvas");
  22507. if (options.width) {
  22508. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22509. }
  22510. else {
  22511. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22512. }
  22513. }
  22514. var textureSize = this.getSize();
  22515. this._canvas.width = textureSize.width;
  22516. this._canvas.height = textureSize.height;
  22517. this._context = this._canvas.getContext("2d");
  22518. }
  22519. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22520. get: function () {
  22521. return true;
  22522. },
  22523. enumerable: true,
  22524. configurable: true
  22525. });
  22526. DynamicTexture.prototype.scale = function (ratio) {
  22527. var textureSize = this.getSize();
  22528. textureSize.width *= ratio;
  22529. textureSize.height *= ratio;
  22530. this._canvas.width = textureSize.width;
  22531. this._canvas.height = textureSize.height;
  22532. this.releaseInternalTexture();
  22533. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22534. };
  22535. DynamicTexture.prototype.getContext = function () {
  22536. return this._context;
  22537. };
  22538. DynamicTexture.prototype.clear = function () {
  22539. var size = this.getSize();
  22540. this._context.fillRect(0, 0, size.width, size.height);
  22541. };
  22542. DynamicTexture.prototype.update = function (invertY) {
  22543. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22544. };
  22545. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22546. if (update === void 0) { update = true; }
  22547. var size = this.getSize();
  22548. if (clearColor) {
  22549. this._context.fillStyle = clearColor;
  22550. this._context.fillRect(0, 0, size.width, size.height);
  22551. }
  22552. this._context.font = font;
  22553. if (x === null) {
  22554. var textSize = this._context.measureText(text);
  22555. x = (size.width - textSize.width) / 2;
  22556. }
  22557. this._context.fillStyle = color;
  22558. this._context.fillText(text, x, y);
  22559. if (update) {
  22560. this.update(invertY);
  22561. }
  22562. };
  22563. DynamicTexture.prototype.clone = function () {
  22564. var textureSize = this.getSize();
  22565. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22566. // Base texture
  22567. newTexture.hasAlpha = this.hasAlpha;
  22568. newTexture.level = this.level;
  22569. // Dynamic Texture
  22570. newTexture.wrapU = this.wrapU;
  22571. newTexture.wrapV = this.wrapV;
  22572. return newTexture;
  22573. };
  22574. return DynamicTexture;
  22575. })(BABYLON.Texture);
  22576. BABYLON.DynamicTexture = DynamicTexture;
  22577. })(BABYLON || (BABYLON = {}));
  22578. var BABYLON;
  22579. (function (BABYLON) {
  22580. var VideoTexture = (function (_super) {
  22581. __extends(VideoTexture, _super);
  22582. /**
  22583. * Creates a video texture.
  22584. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22585. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22586. * @param {BABYLON.Scene} scene is obviously the current scene.
  22587. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22588. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22589. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22590. */
  22591. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22592. var _this = this;
  22593. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22594. if (invertY === void 0) { invertY = false; }
  22595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22596. _super.call(this, null, scene, !generateMipMaps, invertY);
  22597. this._autoLaunch = true;
  22598. var urls;
  22599. this.name = name;
  22600. if (urlsOrVideo instanceof HTMLVideoElement) {
  22601. this.video = urlsOrVideo;
  22602. }
  22603. else {
  22604. urls = urlsOrVideo;
  22605. this.video = document.createElement("video");
  22606. this.video.autoplay = false;
  22607. this.video.loop = true;
  22608. }
  22609. this._generateMipMaps = generateMipMaps;
  22610. this._samplingMode = samplingMode;
  22611. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22612. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22613. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22614. }
  22615. else {
  22616. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22617. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22618. this._generateMipMaps = false;
  22619. }
  22620. if (urls) {
  22621. this.video.addEventListener("canplaythrough", function () {
  22622. _this._createTexture();
  22623. });
  22624. urls.forEach(function (url) {
  22625. var source = document.createElement("source");
  22626. source.src = url;
  22627. _this.video.appendChild(source);
  22628. });
  22629. }
  22630. else {
  22631. this._createTexture();
  22632. }
  22633. this._lastUpdate = BABYLON.Tools.Now;
  22634. }
  22635. VideoTexture.prototype._createTexture = function () {
  22636. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22637. this._texture.isReady = true;
  22638. };
  22639. VideoTexture.prototype.update = function () {
  22640. if (this._autoLaunch) {
  22641. this._autoLaunch = false;
  22642. this.video.play();
  22643. }
  22644. var now = BABYLON.Tools.Now;
  22645. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22646. return false;
  22647. }
  22648. this._lastUpdate = now;
  22649. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22650. return true;
  22651. };
  22652. return VideoTexture;
  22653. })(BABYLON.Texture);
  22654. BABYLON.VideoTexture = VideoTexture;
  22655. })(BABYLON || (BABYLON = {}));
  22656. var BABYLON;
  22657. (function (BABYLON) {
  22658. var CustomProceduralTexture = (function (_super) {
  22659. __extends(CustomProceduralTexture, _super);
  22660. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22661. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22662. this._animate = true;
  22663. this._time = 0;
  22664. this._texturePath = texturePath;
  22665. //Try to load json
  22666. this.loadJson(texturePath);
  22667. this.refreshRate = 1;
  22668. }
  22669. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22670. var _this = this;
  22671. var that = this;
  22672. function noConfigFile() {
  22673. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22674. try {
  22675. that.setFragment(that._texturePath);
  22676. }
  22677. catch (ex) {
  22678. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22679. }
  22680. }
  22681. var configFileUrl = jsonUrl + "/config.json";
  22682. var xhr = new XMLHttpRequest();
  22683. xhr.open("GET", configFileUrl, true);
  22684. xhr.addEventListener("load", function () {
  22685. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22686. try {
  22687. _this._config = JSON.parse(xhr.response);
  22688. _this.updateShaderUniforms();
  22689. _this.updateTextures();
  22690. _this.setFragment(_this._texturePath + "/custom");
  22691. _this._animate = _this._config.animate;
  22692. _this.refreshRate = _this._config.refreshrate;
  22693. }
  22694. catch (ex) {
  22695. noConfigFile();
  22696. }
  22697. }
  22698. else {
  22699. noConfigFile();
  22700. }
  22701. }, false);
  22702. xhr.addEventListener("error", function () {
  22703. noConfigFile();
  22704. }, false);
  22705. try {
  22706. xhr.send();
  22707. }
  22708. catch (ex) {
  22709. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22710. }
  22711. };
  22712. CustomProceduralTexture.prototype.isReady = function () {
  22713. if (!_super.prototype.isReady.call(this)) {
  22714. return false;
  22715. }
  22716. for (var name in this._textures) {
  22717. var texture = this._textures[name];
  22718. if (!texture.isReady()) {
  22719. return false;
  22720. }
  22721. }
  22722. return true;
  22723. };
  22724. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22725. if (this._animate) {
  22726. this._time += this.getScene().getAnimationRatio() * 0.03;
  22727. this.updateShaderUniforms();
  22728. }
  22729. _super.prototype.render.call(this, useCameraPostProcess);
  22730. };
  22731. CustomProceduralTexture.prototype.updateTextures = function () {
  22732. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22733. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22734. }
  22735. };
  22736. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22737. if (this._config) {
  22738. for (var j = 0; j < this._config.uniforms.length; j++) {
  22739. var uniform = this._config.uniforms[j];
  22740. switch (uniform.type) {
  22741. case "float":
  22742. this.setFloat(uniform.name, uniform.value);
  22743. break;
  22744. case "color3":
  22745. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22746. break;
  22747. case "color4":
  22748. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22749. break;
  22750. case "vector2":
  22751. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22752. break;
  22753. case "vector3":
  22754. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22755. break;
  22756. }
  22757. }
  22758. }
  22759. this.setFloat("time", this._time);
  22760. };
  22761. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22762. get: function () {
  22763. return this._animate;
  22764. },
  22765. set: function (value) {
  22766. this._animate = value;
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. return CustomProceduralTexture;
  22772. })(BABYLON.ProceduralTexture);
  22773. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22774. })(BABYLON || (BABYLON = {}));
  22775. var BABYLON;
  22776. (function (BABYLON) {
  22777. var EffectFallbacks = (function () {
  22778. function EffectFallbacks() {
  22779. this._defines = {};
  22780. this._currentRank = 32;
  22781. this._maxRank = -1;
  22782. }
  22783. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22784. if (!this._defines[rank]) {
  22785. if (rank < this._currentRank) {
  22786. this._currentRank = rank;
  22787. }
  22788. if (rank > this._maxRank) {
  22789. this._maxRank = rank;
  22790. }
  22791. this._defines[rank] = new Array();
  22792. }
  22793. this._defines[rank].push(define);
  22794. };
  22795. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22796. this._meshRank = rank;
  22797. this._mesh = mesh;
  22798. if (rank > this._maxRank) {
  22799. this._maxRank = rank;
  22800. }
  22801. };
  22802. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22803. get: function () {
  22804. return this._currentRank <= this._maxRank;
  22805. },
  22806. enumerable: true,
  22807. configurable: true
  22808. });
  22809. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22810. var currentFallbacks = this._defines[this._currentRank];
  22811. for (var index = 0; index < currentFallbacks.length; index++) {
  22812. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22813. }
  22814. if (this._mesh && this._currentRank === this._meshRank) {
  22815. this._mesh.computeBonesUsingShaders = false;
  22816. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22817. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22818. }
  22819. this._currentRank++;
  22820. return currentDefines;
  22821. };
  22822. return EffectFallbacks;
  22823. })();
  22824. BABYLON.EffectFallbacks = EffectFallbacks;
  22825. var Effect = (function () {
  22826. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22827. var _this = this;
  22828. this._isReady = false;
  22829. this._compilationError = "";
  22830. this._valueCache = {};
  22831. this._engine = engine;
  22832. this.name = baseName;
  22833. this.defines = defines;
  22834. this._uniformsNames = uniformsNames.concat(samplers);
  22835. this._samplers = samplers;
  22836. this._attributesNames = attributesNames;
  22837. this.onError = onError;
  22838. this.onCompiled = onCompiled;
  22839. this._indexParameters = indexParameters;
  22840. var vertexSource;
  22841. var fragmentSource;
  22842. if (baseName.vertexElement) {
  22843. vertexSource = document.getElementById(baseName.vertexElement);
  22844. if (!vertexSource) {
  22845. vertexSource = baseName.vertexElement;
  22846. }
  22847. }
  22848. else {
  22849. vertexSource = baseName.vertex || baseName;
  22850. }
  22851. if (baseName.fragmentElement) {
  22852. fragmentSource = document.getElementById(baseName.fragmentElement);
  22853. if (!fragmentSource) {
  22854. fragmentSource = baseName.fragmentElement;
  22855. }
  22856. }
  22857. else {
  22858. fragmentSource = baseName.fragment || baseName;
  22859. }
  22860. this._loadVertexShader(vertexSource, function (vertexCode) {
  22861. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22862. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22863. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22864. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22865. });
  22866. });
  22867. });
  22868. });
  22869. }
  22870. // Properties
  22871. Effect.prototype.isReady = function () {
  22872. return this._isReady;
  22873. };
  22874. Effect.prototype.getProgram = function () {
  22875. return this._program;
  22876. };
  22877. Effect.prototype.getAttributesNames = function () {
  22878. return this._attributesNames;
  22879. };
  22880. Effect.prototype.getAttributeLocation = function (index) {
  22881. return this._attributes[index];
  22882. };
  22883. Effect.prototype.getAttributeLocationByName = function (name) {
  22884. var index = this._attributesNames.indexOf(name);
  22885. return this._attributes[index];
  22886. };
  22887. Effect.prototype.getAttributesCount = function () {
  22888. return this._attributes.length;
  22889. };
  22890. Effect.prototype.getUniformIndex = function (uniformName) {
  22891. return this._uniformsNames.indexOf(uniformName);
  22892. };
  22893. Effect.prototype.getUniform = function (uniformName) {
  22894. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22895. };
  22896. Effect.prototype.getSamplers = function () {
  22897. return this._samplers;
  22898. };
  22899. Effect.prototype.getCompilationError = function () {
  22900. return this._compilationError;
  22901. };
  22902. // Methods
  22903. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22904. // DOM element ?
  22905. if (vertex instanceof HTMLElement) {
  22906. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22907. callback(vertexCode);
  22908. return;
  22909. }
  22910. // Is in local store ?
  22911. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22912. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22913. return;
  22914. }
  22915. var vertexShaderUrl;
  22916. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22917. vertexShaderUrl = vertex;
  22918. }
  22919. else {
  22920. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22921. }
  22922. // Vertex shader
  22923. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22924. };
  22925. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22926. // DOM element ?
  22927. if (fragment instanceof HTMLElement) {
  22928. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22929. callback(fragmentCode);
  22930. return;
  22931. }
  22932. // Is in local store ?
  22933. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22934. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22935. return;
  22936. }
  22937. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22938. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22939. return;
  22940. }
  22941. var fragmentShaderUrl;
  22942. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22943. fragmentShaderUrl = fragment;
  22944. }
  22945. else {
  22946. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22947. }
  22948. // Fragment shader
  22949. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22950. };
  22951. Effect.prototype._dumpShadersName = function () {
  22952. if (this.name.vertexElement) {
  22953. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22954. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22955. }
  22956. else if (this.name.vertex) {
  22957. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22958. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22959. }
  22960. else {
  22961. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22962. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22963. }
  22964. };
  22965. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22966. var _this = this;
  22967. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22968. var match = regex.exec(sourceCode);
  22969. var returnValue = new String(sourceCode);
  22970. while (match != null) {
  22971. var includeFile = match[1];
  22972. if (Effect.IncludesShadersStore[includeFile]) {
  22973. // Substitution
  22974. var includeContent = Effect.IncludesShadersStore[includeFile];
  22975. if (match[2]) {
  22976. var splits = match[3].split(",");
  22977. for (var index = 0; index < splits.length; index += 2) {
  22978. var source = new RegExp(splits[index], "g");
  22979. var dest = splits[index + 1];
  22980. includeContent = includeContent.replace(source, dest);
  22981. }
  22982. }
  22983. if (match[4]) {
  22984. var indexString = match[5];
  22985. if (indexString.indexOf("..") !== -1) {
  22986. var indexSplits = indexString.split("..");
  22987. var minIndex = parseInt(indexSplits[0]);
  22988. var maxIndex = parseInt(indexSplits[1]);
  22989. var sourceIncludeContent = includeContent.slice(0);
  22990. includeContent = "";
  22991. if (isNaN(maxIndex)) {
  22992. maxIndex = this._indexParameters[indexSplits[1]];
  22993. }
  22994. for (var i = minIndex; i <= maxIndex; i++) {
  22995. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22996. }
  22997. }
  22998. else {
  22999. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23000. }
  23001. }
  23002. // Replace
  23003. returnValue = returnValue.replace(match[0], includeContent);
  23004. }
  23005. else {
  23006. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23007. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23008. Effect.IncludesShadersStore[includeFile] = fileContent;
  23009. _this._processIncludes(returnValue, callback);
  23010. });
  23011. return;
  23012. }
  23013. match = regex.exec(sourceCode);
  23014. }
  23015. callback(returnValue);
  23016. };
  23017. Effect.prototype._processPrecision = function (source) {
  23018. if (source.indexOf("precision highp float") === -1) {
  23019. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23020. source = "precision mediump float;\n" + source;
  23021. }
  23022. else {
  23023. source = "precision highp float;\n" + source;
  23024. }
  23025. }
  23026. else {
  23027. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23028. source = source.replace("precision highp float", "precision mediump float");
  23029. }
  23030. }
  23031. return source;
  23032. };
  23033. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23034. try {
  23035. var engine = this._engine;
  23036. // Precision
  23037. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23038. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23039. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23040. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23041. this._attributes = engine.getAttributes(this._program, attributesNames);
  23042. var index;
  23043. for (index = 0; index < this._samplers.length; index++) {
  23044. var sampler = this.getUniform(this._samplers[index]);
  23045. if (sampler == null) {
  23046. this._samplers.splice(index, 1);
  23047. index--;
  23048. }
  23049. }
  23050. engine.bindSamplers(this);
  23051. this._isReady = true;
  23052. if (this.onCompiled) {
  23053. this.onCompiled(this);
  23054. }
  23055. }
  23056. catch (e) {
  23057. // Let's go through fallbacks then
  23058. if (fallbacks && fallbacks.isMoreFallbacks) {
  23059. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23060. this._dumpShadersName();
  23061. defines = fallbacks.reduce(defines);
  23062. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23063. }
  23064. else {
  23065. BABYLON.Tools.Error("Unable to compile effect: ");
  23066. this._dumpShadersName();
  23067. BABYLON.Tools.Error("Defines: " + defines);
  23068. BABYLON.Tools.Error("Error: " + e.message);
  23069. this._compilationError = e.message;
  23070. if (this.onError) {
  23071. this.onError(this, this._compilationError);
  23072. }
  23073. }
  23074. }
  23075. };
  23076. Object.defineProperty(Effect.prototype, "isSupported", {
  23077. get: function () {
  23078. return this._compilationError === "";
  23079. },
  23080. enumerable: true,
  23081. configurable: true
  23082. });
  23083. Effect.prototype._bindTexture = function (channel, texture) {
  23084. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23085. };
  23086. Effect.prototype.setTexture = function (channel, texture) {
  23087. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23088. };
  23089. Effect.prototype.setTextureArray = function (channel, textures) {
  23090. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23091. var initialPos = this._samplers.indexOf(channel);
  23092. for (var index = 1; index < textures.length; index++) {
  23093. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23094. }
  23095. }
  23096. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23097. };
  23098. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23099. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23100. };
  23101. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23102. var changed = false;
  23103. var cache = this._valueCache[uniformName];
  23104. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23105. changed = true;
  23106. cache = new BABYLON.Matrix();
  23107. }
  23108. var tm = cache.m;
  23109. var om = matrix.m;
  23110. for (var index = 0; index < 16; index++) {
  23111. if (tm[index] !== om[index]) {
  23112. tm[index] = om[index];
  23113. changed = true;
  23114. }
  23115. }
  23116. this._valueCache[uniformName] = cache;
  23117. return changed;
  23118. };
  23119. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23120. var cache = this._valueCache[uniformName];
  23121. if (!cache) {
  23122. cache = [x, y];
  23123. this._valueCache[uniformName] = cache;
  23124. return true;
  23125. }
  23126. var changed = false;
  23127. if (cache[0] !== x) {
  23128. cache[0] = x;
  23129. changed = true;
  23130. }
  23131. if (cache[1] !== y) {
  23132. cache[1] = y;
  23133. changed = true;
  23134. }
  23135. this._valueCache[uniformName] = cache;
  23136. return changed;
  23137. };
  23138. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23139. var cache = this._valueCache[uniformName];
  23140. if (!cache) {
  23141. cache = [x, y, z];
  23142. this._valueCache[uniformName] = cache;
  23143. return true;
  23144. }
  23145. var changed = false;
  23146. if (cache[0] !== x) {
  23147. cache[0] = x;
  23148. changed = true;
  23149. }
  23150. if (cache[1] !== y) {
  23151. cache[1] = y;
  23152. changed = true;
  23153. }
  23154. if (cache[2] !== z) {
  23155. cache[2] = z;
  23156. changed = true;
  23157. }
  23158. this._valueCache[uniformName] = cache;
  23159. return changed;
  23160. };
  23161. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23162. var cache = this._valueCache[uniformName];
  23163. if (!cache) {
  23164. cache = [x, y, z, w];
  23165. this._valueCache[uniformName] = cache;
  23166. return true;
  23167. }
  23168. var changed = false;
  23169. if (cache[0] !== x) {
  23170. cache[0] = x;
  23171. changed = true;
  23172. }
  23173. if (cache[1] !== y) {
  23174. cache[1] = y;
  23175. changed = true;
  23176. }
  23177. if (cache[2] !== z) {
  23178. cache[2] = z;
  23179. changed = true;
  23180. }
  23181. if (cache[3] !== w) {
  23182. cache[3] = w;
  23183. changed = true;
  23184. }
  23185. this._valueCache[uniformName] = cache;
  23186. return changed;
  23187. };
  23188. Effect.prototype.setArray = function (uniformName, array) {
  23189. this._valueCache[uniformName] = null;
  23190. this._engine.setArray(this.getUniform(uniformName), array);
  23191. return this;
  23192. };
  23193. Effect.prototype.setArray2 = function (uniformName, array) {
  23194. this._valueCache[uniformName] = null;
  23195. this._engine.setArray2(this.getUniform(uniformName), array);
  23196. return this;
  23197. };
  23198. Effect.prototype.setArray3 = function (uniformName, array) {
  23199. this._valueCache[uniformName] = null;
  23200. this._engine.setArray3(this.getUniform(uniformName), array);
  23201. return this;
  23202. };
  23203. Effect.prototype.setArray4 = function (uniformName, array) {
  23204. this._valueCache[uniformName] = null;
  23205. this._engine.setArray4(this.getUniform(uniformName), array);
  23206. return this;
  23207. };
  23208. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23209. this._valueCache[uniformName] = null;
  23210. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23211. return this;
  23212. };
  23213. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23214. if (this._cacheMatrix(uniformName, matrix)) {
  23215. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23216. }
  23217. return this;
  23218. };
  23219. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23220. this._valueCache[uniformName] = null;
  23221. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23222. return this;
  23223. };
  23224. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23225. this._valueCache[uniformName] = null;
  23226. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23227. return this;
  23228. };
  23229. Effect.prototype.setFloat = function (uniformName, value) {
  23230. var cache = this._valueCache[uniformName];
  23231. if (cache && cache === value)
  23232. return this;
  23233. this._valueCache[uniformName] = value;
  23234. this._engine.setFloat(this.getUniform(uniformName), value);
  23235. return this;
  23236. };
  23237. Effect.prototype.setBool = function (uniformName, bool) {
  23238. var cache = this._valueCache[uniformName];
  23239. if (cache && cache === bool)
  23240. return this;
  23241. this._valueCache[uniformName] = bool;
  23242. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23243. return this;
  23244. };
  23245. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23246. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23247. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23248. }
  23249. return this;
  23250. };
  23251. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23252. if (this._cacheFloat2(uniformName, x, y)) {
  23253. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23254. }
  23255. return this;
  23256. };
  23257. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23258. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23259. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23260. }
  23261. return this;
  23262. };
  23263. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23264. if (this._cacheFloat3(uniformName, x, y, z)) {
  23265. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23266. }
  23267. return this;
  23268. };
  23269. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23270. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23271. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23272. }
  23273. return this;
  23274. };
  23275. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23276. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23277. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23278. }
  23279. return this;
  23280. };
  23281. Effect.prototype.setColor3 = function (uniformName, color3) {
  23282. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23283. this._engine.setColor3(this.getUniform(uniformName), color3);
  23284. }
  23285. return this;
  23286. };
  23287. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23288. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23289. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23290. }
  23291. return this;
  23292. };
  23293. // Statics
  23294. Effect.ShadersStore = {};
  23295. Effect.IncludesShadersStore = {};
  23296. return Effect;
  23297. })();
  23298. BABYLON.Effect = Effect;
  23299. })(BABYLON || (BABYLON = {}));
  23300. var BABYLON;
  23301. (function (BABYLON) {
  23302. var MaterialHelper = (function () {
  23303. function MaterialHelper() {
  23304. }
  23305. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23306. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23307. var lightIndex = 0;
  23308. var needNormals = false;
  23309. var needRebuild = false;
  23310. for (var index = 0; index < scene.lights.length; index++) {
  23311. var light = scene.lights[index];
  23312. if (!light.isEnabled()) {
  23313. continue;
  23314. }
  23315. // Excluded check
  23316. if (light._excludedMeshesIds.length > 0) {
  23317. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23318. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23319. if (excludedMesh) {
  23320. light.excludedMeshes.push(excludedMesh);
  23321. }
  23322. }
  23323. light._excludedMeshesIds = [];
  23324. }
  23325. // Included check
  23326. if (light._includedOnlyMeshesIds.length > 0) {
  23327. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23328. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23329. if (includedOnlyMesh) {
  23330. light.includedOnlyMeshes.push(includedOnlyMesh);
  23331. }
  23332. }
  23333. light._includedOnlyMeshesIds = [];
  23334. }
  23335. if (!light.canAffectMesh(mesh)) {
  23336. continue;
  23337. }
  23338. needNormals = true;
  23339. if (defines["LIGHT" + lightIndex] === undefined) {
  23340. needRebuild = true;
  23341. }
  23342. defines["LIGHT" + lightIndex] = true;
  23343. var type;
  23344. if (light instanceof BABYLON.SpotLight) {
  23345. type = "SPOTLIGHT" + lightIndex;
  23346. }
  23347. else if (light instanceof BABYLON.HemisphericLight) {
  23348. type = "HEMILIGHT" + lightIndex;
  23349. }
  23350. else if (light instanceof BABYLON.PointLight) {
  23351. type = "POINTLIGHT" + lightIndex;
  23352. }
  23353. else {
  23354. type = "DIRLIGHT" + lightIndex;
  23355. }
  23356. if (defines[type] === undefined) {
  23357. needRebuild = true;
  23358. }
  23359. defines[type] = true;
  23360. // Specular
  23361. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23362. defines["SPECULARTERM"] = true;
  23363. }
  23364. // Shadows
  23365. if (scene.shadowsEnabled) {
  23366. var shadowGenerator = light.getShadowGenerator();
  23367. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23368. if (defines["SHADOW" + lightIndex] === undefined) {
  23369. needRebuild = true;
  23370. }
  23371. defines["SHADOW" + lightIndex] = true;
  23372. defines["SHADOWS"] = true;
  23373. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23374. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23375. needRebuild = true;
  23376. }
  23377. defines["SHADOWVSM" + lightIndex] = true;
  23378. }
  23379. if (shadowGenerator.usePoissonSampling) {
  23380. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23381. needRebuild = true;
  23382. }
  23383. defines["SHADOWPCF" + lightIndex] = true;
  23384. }
  23385. }
  23386. }
  23387. lightIndex++;
  23388. if (lightIndex === maxSimultaneousLights)
  23389. break;
  23390. }
  23391. if (needRebuild) {
  23392. defines.rebuild();
  23393. }
  23394. return needNormals;
  23395. };
  23396. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23397. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23398. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23399. if (!defines["LIGHT" + lightIndex]) {
  23400. break;
  23401. }
  23402. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23403. samplersList.push("shadowSampler" + lightIndex);
  23404. }
  23405. };
  23406. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23407. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23408. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23409. if (!defines["LIGHT" + lightIndex]) {
  23410. break;
  23411. }
  23412. if (lightIndex > 0) {
  23413. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23414. }
  23415. if (defines["SHADOW" + lightIndex]) {
  23416. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23417. }
  23418. if (defines["SHADOWPCF" + lightIndex]) {
  23419. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23420. }
  23421. if (defines["SHADOWVSM" + lightIndex]) {
  23422. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23423. }
  23424. }
  23425. };
  23426. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23427. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23428. fallbacks.addCPUSkinningFallback(0, mesh);
  23429. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23430. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23431. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23432. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23433. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23434. }
  23435. }
  23436. };
  23437. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23438. if (defines["INSTANCES"]) {
  23439. attribs.push("world0");
  23440. attribs.push("world1");
  23441. attribs.push("world2");
  23442. attribs.push("world3");
  23443. }
  23444. };
  23445. // Bindings
  23446. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23447. var shadowGenerator = light.getShadowGenerator();
  23448. if (mesh.receiveShadows && shadowGenerator) {
  23449. if (!light.needCube()) {
  23450. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23451. }
  23452. else {
  23453. if (!depthValuesAlreadySet) {
  23454. depthValuesAlreadySet = true;
  23455. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23456. }
  23457. }
  23458. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23459. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23460. }
  23461. return depthValuesAlreadySet;
  23462. };
  23463. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23464. if (light instanceof BABYLON.PointLight) {
  23465. // Point Light
  23466. light.transferToEffect(effect, "vLightData" + lightIndex);
  23467. }
  23468. else if (light instanceof BABYLON.DirectionalLight) {
  23469. // Directional Light
  23470. light.transferToEffect(effect, "vLightData" + lightIndex);
  23471. }
  23472. else if (light instanceof BABYLON.SpotLight) {
  23473. // Spot Light
  23474. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23475. }
  23476. else if (light instanceof BABYLON.HemisphericLight) {
  23477. // Hemispheric Light
  23478. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23479. }
  23480. };
  23481. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23482. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23483. var lightIndex = 0;
  23484. var depthValuesAlreadySet = false;
  23485. for (var index = 0; index < scene.lights.length; index++) {
  23486. var light = scene.lights[index];
  23487. if (!light.isEnabled()) {
  23488. continue;
  23489. }
  23490. if (!light.canAffectMesh(mesh)) {
  23491. continue;
  23492. }
  23493. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23494. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23495. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23496. if (defines["SPECULARTERM"]) {
  23497. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23498. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23499. }
  23500. // Shadows
  23501. if (scene.shadowsEnabled) {
  23502. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23503. }
  23504. lightIndex++;
  23505. if (lightIndex === maxSimultaneousLights)
  23506. break;
  23507. }
  23508. };
  23509. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23510. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23511. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23512. effect.setColor3("vFogColor", scene.fogColor);
  23513. }
  23514. };
  23515. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23516. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23517. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23518. }
  23519. };
  23520. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23521. if (defines["LOGARITHMICDEPTH"]) {
  23522. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23523. }
  23524. };
  23525. MaterialHelper.BindClipPlane = function (effect, scene) {
  23526. if (scene.clipPlane) {
  23527. var clipPlane = scene.clipPlane;
  23528. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23529. }
  23530. };
  23531. return MaterialHelper;
  23532. })();
  23533. BABYLON.MaterialHelper = MaterialHelper;
  23534. })(BABYLON || (BABYLON = {}));
  23535. var BABYLON;
  23536. (function (BABYLON) {
  23537. var FresnelParameters = (function () {
  23538. function FresnelParameters() {
  23539. this.isEnabled = true;
  23540. this.leftColor = BABYLON.Color3.White();
  23541. this.rightColor = BABYLON.Color3.Black();
  23542. this.bias = 0;
  23543. this.power = 1;
  23544. }
  23545. FresnelParameters.prototype.clone = function () {
  23546. var newFresnelParameters = new FresnelParameters();
  23547. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23548. return new FresnelParameters;
  23549. };
  23550. FresnelParameters.prototype.serialize = function () {
  23551. var serializationObject = {};
  23552. serializationObject.isEnabled = this.isEnabled;
  23553. serializationObject.leftColor = this.leftColor;
  23554. serializationObject.rightColor = this.rightColor;
  23555. serializationObject.bias = this.bias;
  23556. serializationObject.power = this.power;
  23557. return serializationObject;
  23558. };
  23559. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23560. var fresnelParameters = new FresnelParameters();
  23561. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23562. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23563. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23564. fresnelParameters.bias = parsedFresnelParameters.bias;
  23565. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23566. return fresnelParameters;
  23567. };
  23568. return FresnelParameters;
  23569. })();
  23570. BABYLON.FresnelParameters = FresnelParameters;
  23571. })(BABYLON || (BABYLON = {}));
  23572. var BABYLON;
  23573. (function (BABYLON) {
  23574. var MaterialDefines = (function () {
  23575. function MaterialDefines() {
  23576. }
  23577. MaterialDefines.prototype.rebuild = function () {
  23578. if (this._keys) {
  23579. delete this._keys;
  23580. }
  23581. this._keys = Object.keys(this);
  23582. };
  23583. MaterialDefines.prototype.isEqual = function (other) {
  23584. if (this._keys.length !== other._keys.length) {
  23585. return false;
  23586. }
  23587. for (var index = 0; index < this._keys.length; index++) {
  23588. var prop = this._keys[index];
  23589. if (this[prop] !== other[prop]) {
  23590. return false;
  23591. }
  23592. }
  23593. return true;
  23594. };
  23595. MaterialDefines.prototype.cloneTo = function (other) {
  23596. if (this._keys.length !== other._keys.length) {
  23597. other._keys = this._keys.slice(0);
  23598. }
  23599. for (var index = 0; index < this._keys.length; index++) {
  23600. var prop = this._keys[index];
  23601. other[prop] = this[prop];
  23602. }
  23603. };
  23604. MaterialDefines.prototype.reset = function () {
  23605. for (var index = 0; index < this._keys.length; index++) {
  23606. var prop = this._keys[index];
  23607. if (typeof (this[prop]) === "number") {
  23608. this[prop] = 0;
  23609. }
  23610. else {
  23611. this[prop] = false;
  23612. }
  23613. }
  23614. };
  23615. MaterialDefines.prototype.toString = function () {
  23616. var result = "";
  23617. for (var index = 0; index < this._keys.length; index++) {
  23618. var prop = this._keys[index];
  23619. if (typeof (this[prop]) === "number") {
  23620. result += "#define " + prop + " " + this[prop] + "\n";
  23621. }
  23622. else if (this[prop]) {
  23623. result += "#define " + prop + "\n";
  23624. }
  23625. }
  23626. return result;
  23627. };
  23628. return MaterialDefines;
  23629. })();
  23630. BABYLON.MaterialDefines = MaterialDefines;
  23631. var Material = (function () {
  23632. function Material(name, scene, doNotAdd) {
  23633. this.name = name;
  23634. this.checkReadyOnEveryCall = false;
  23635. this.checkReadyOnlyOnce = false;
  23636. this.state = "";
  23637. this.alpha = 1.0;
  23638. this.backFaceCulling = true;
  23639. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23640. /**
  23641. * An event triggered when the material is disposed.
  23642. * @type {BABYLON.Observable}
  23643. */
  23644. this.onDisposeObservable = new BABYLON.Observable();
  23645. /**
  23646. * An event triggered when the material is compiled.
  23647. * @type {BABYLON.Observable}
  23648. */
  23649. this.onBindObservable = new BABYLON.Observable();
  23650. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23651. this.disableDepthWrite = false;
  23652. this.fogEnabled = true;
  23653. this.pointSize = 1.0;
  23654. this.zOffset = 0;
  23655. this._wasPreviouslyReady = false;
  23656. this._fillMode = Material.TriangleFillMode;
  23657. this.id = name;
  23658. this._scene = scene;
  23659. if (!doNotAdd) {
  23660. scene.materials.push(this);
  23661. }
  23662. }
  23663. Object.defineProperty(Material, "TriangleFillMode", {
  23664. get: function () {
  23665. return Material._TriangleFillMode;
  23666. },
  23667. enumerable: true,
  23668. configurable: true
  23669. });
  23670. Object.defineProperty(Material, "WireFrameFillMode", {
  23671. get: function () {
  23672. return Material._WireFrameFillMode;
  23673. },
  23674. enumerable: true,
  23675. configurable: true
  23676. });
  23677. Object.defineProperty(Material, "PointFillMode", {
  23678. get: function () {
  23679. return Material._PointFillMode;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23685. get: function () {
  23686. return Material._ClockWiseSideOrientation;
  23687. },
  23688. enumerable: true,
  23689. configurable: true
  23690. });
  23691. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23692. get: function () {
  23693. return Material._CounterClockWiseSideOrientation;
  23694. },
  23695. enumerable: true,
  23696. configurable: true
  23697. });
  23698. Object.defineProperty(Material.prototype, "onDispose", {
  23699. set: function (callback) {
  23700. if (this._onDisposeObserver) {
  23701. this.onDisposeObservable.remove(this._onDisposeObserver);
  23702. }
  23703. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. Object.defineProperty(Material.prototype, "onBind", {
  23709. set: function (callback) {
  23710. if (this._onBindObserver) {
  23711. this.onBindObservable.remove(this._onBindObserver);
  23712. }
  23713. this._onBindObserver = this.onBindObservable.add(callback);
  23714. },
  23715. enumerable: true,
  23716. configurable: true
  23717. });
  23718. Object.defineProperty(Material.prototype, "wireframe", {
  23719. get: function () {
  23720. return this._fillMode === Material.WireFrameFillMode;
  23721. },
  23722. set: function (value) {
  23723. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23724. },
  23725. enumerable: true,
  23726. configurable: true
  23727. });
  23728. Object.defineProperty(Material.prototype, "pointsCloud", {
  23729. get: function () {
  23730. return this._fillMode === Material.PointFillMode;
  23731. },
  23732. set: function (value) {
  23733. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23734. },
  23735. enumerable: true,
  23736. configurable: true
  23737. });
  23738. Object.defineProperty(Material.prototype, "fillMode", {
  23739. get: function () {
  23740. return this._fillMode;
  23741. },
  23742. set: function (value) {
  23743. this._fillMode = value;
  23744. },
  23745. enumerable: true,
  23746. configurable: true
  23747. });
  23748. /**
  23749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23750. * subclasses should override adding information pertainent to themselves
  23751. */
  23752. Material.prototype.toString = function (fullDetails) {
  23753. var ret = "Name: " + this.name;
  23754. if (fullDetails) {
  23755. }
  23756. return ret;
  23757. };
  23758. Object.defineProperty(Material.prototype, "isFrozen", {
  23759. get: function () {
  23760. return this.checkReadyOnlyOnce;
  23761. },
  23762. enumerable: true,
  23763. configurable: true
  23764. });
  23765. Material.prototype.freeze = function () {
  23766. this.checkReadyOnlyOnce = true;
  23767. };
  23768. Material.prototype.unfreeze = function () {
  23769. this.checkReadyOnlyOnce = false;
  23770. };
  23771. Material.prototype.isReady = function (mesh, useInstances) {
  23772. return true;
  23773. };
  23774. Material.prototype.getEffect = function () {
  23775. return this._effect;
  23776. };
  23777. Material.prototype.getScene = function () {
  23778. return this._scene;
  23779. };
  23780. Material.prototype.needAlphaBlending = function () {
  23781. return (this.alpha < 1.0);
  23782. };
  23783. Material.prototype.needAlphaTesting = function () {
  23784. return false;
  23785. };
  23786. Material.prototype.getAlphaTestTexture = function () {
  23787. return null;
  23788. };
  23789. Material.prototype.markDirty = function () {
  23790. this._wasPreviouslyReady = false;
  23791. };
  23792. Material.prototype._preBind = function () {
  23793. var engine = this._scene.getEngine();
  23794. engine.enableEffect(this._effect);
  23795. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23796. };
  23797. Material.prototype.bind = function (world, mesh) {
  23798. this._scene._cachedMaterial = this;
  23799. this.onBindObservable.notifyObservers(mesh);
  23800. if (this.disableDepthWrite) {
  23801. var engine = this._scene.getEngine();
  23802. this._cachedDepthWriteState = engine.getDepthWrite();
  23803. engine.setDepthWrite(false);
  23804. }
  23805. };
  23806. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23807. };
  23808. Material.prototype.unbind = function () {
  23809. if (this.disableDepthWrite) {
  23810. var engine = this._scene.getEngine();
  23811. engine.setDepthWrite(this._cachedDepthWriteState);
  23812. }
  23813. };
  23814. Material.prototype.clone = function (name) {
  23815. return null;
  23816. };
  23817. Material.prototype.getBindedMeshes = function () {
  23818. var result = new Array();
  23819. for (var index = 0; index < this._scene.meshes.length; index++) {
  23820. var mesh = this._scene.meshes[index];
  23821. if (mesh.material === this) {
  23822. result.push(mesh);
  23823. }
  23824. }
  23825. return result;
  23826. };
  23827. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23828. // Animations
  23829. this.getScene().stopAnimation(this);
  23830. // Remove from scene
  23831. var index = this._scene.materials.indexOf(this);
  23832. if (index >= 0) {
  23833. this._scene.materials.splice(index, 1);
  23834. }
  23835. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23836. if (forceDisposeEffect && this._effect) {
  23837. this._scene.getEngine()._releaseEffect(this._effect);
  23838. this._effect = null;
  23839. }
  23840. // Remove from meshes
  23841. for (index = 0; index < this._scene.meshes.length; index++) {
  23842. var mesh = this._scene.meshes[index];
  23843. if (mesh.material === this) {
  23844. mesh.material = null;
  23845. }
  23846. }
  23847. // Callback
  23848. this.onDisposeObservable.notifyObservers(this);
  23849. this.onDisposeObservable.clear();
  23850. this.onBindObservable.clear();
  23851. };
  23852. Material.prototype.serialize = function () {
  23853. return BABYLON.SerializationHelper.Serialize(this);
  23854. };
  23855. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23856. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23857. multiMaterial.id = parsedMultiMaterial.id;
  23858. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23859. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23860. var subMatId = parsedMultiMaterial.materials[matIndex];
  23861. if (subMatId) {
  23862. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23863. }
  23864. else {
  23865. multiMaterial.subMaterials.push(null);
  23866. }
  23867. }
  23868. return multiMaterial;
  23869. };
  23870. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23871. if (!parsedMaterial.customType) {
  23872. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23873. }
  23874. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23875. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23876. ;
  23877. };
  23878. Material._TriangleFillMode = 0;
  23879. Material._WireFrameFillMode = 1;
  23880. Material._PointFillMode = 2;
  23881. Material._ClockWiseSideOrientation = 0;
  23882. Material._CounterClockWiseSideOrientation = 1;
  23883. __decorate([
  23884. BABYLON.serialize()
  23885. ], Material.prototype, "id", void 0);
  23886. __decorate([
  23887. BABYLON.serialize()
  23888. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23889. __decorate([
  23890. BABYLON.serialize()
  23891. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23892. __decorate([
  23893. BABYLON.serialize()
  23894. ], Material.prototype, "state", void 0);
  23895. __decorate([
  23896. BABYLON.serialize()
  23897. ], Material.prototype, "alpha", void 0);
  23898. __decorate([
  23899. BABYLON.serialize()
  23900. ], Material.prototype, "backFaceCulling", void 0);
  23901. __decorate([
  23902. BABYLON.serialize()
  23903. ], Material.prototype, "sideOrientation", void 0);
  23904. __decorate([
  23905. BABYLON.serialize()
  23906. ], Material.prototype, "alphaMode", void 0);
  23907. __decorate([
  23908. BABYLON.serialize()
  23909. ], Material.prototype, "disableDepthWrite", void 0);
  23910. __decorate([
  23911. BABYLON.serialize()
  23912. ], Material.prototype, "fogEnabled", void 0);
  23913. __decorate([
  23914. BABYLON.serialize()
  23915. ], Material.prototype, "pointSize", void 0);
  23916. __decorate([
  23917. BABYLON.serialize()
  23918. ], Material.prototype, "zOffset", void 0);
  23919. __decorate([
  23920. BABYLON.serialize()
  23921. ], Material.prototype, "wireframe", null);
  23922. __decorate([
  23923. BABYLON.serialize()
  23924. ], Material.prototype, "pointsCloud", null);
  23925. __decorate([
  23926. BABYLON.serialize()
  23927. ], Material.prototype, "fillMode", null);
  23928. return Material;
  23929. })();
  23930. BABYLON.Material = Material;
  23931. })(BABYLON || (BABYLON = {}));
  23932. var BABYLON;
  23933. (function (BABYLON) {
  23934. var StandardMaterialDefines = (function (_super) {
  23935. __extends(StandardMaterialDefines, _super);
  23936. function StandardMaterialDefines() {
  23937. _super.call(this);
  23938. this.DIFFUSE = false;
  23939. this.AMBIENT = false;
  23940. this.OPACITY = false;
  23941. this.OPACITYRGB = false;
  23942. this.REFLECTION = false;
  23943. this.EMISSIVE = false;
  23944. this.SPECULAR = false;
  23945. this.BUMP = false;
  23946. this.PARALLAX = false;
  23947. this.PARALLAXOCCLUSION = false;
  23948. this.SPECULAROVERALPHA = false;
  23949. this.CLIPPLANE = false;
  23950. this.ALPHATEST = false;
  23951. this.ALPHAFROMDIFFUSE = false;
  23952. this.POINTSIZE = false;
  23953. this.FOG = false;
  23954. this.SPECULARTERM = false;
  23955. this.DIFFUSEFRESNEL = false;
  23956. this.OPACITYFRESNEL = false;
  23957. this.REFLECTIONFRESNEL = false;
  23958. this.REFRACTIONFRESNEL = false;
  23959. this.EMISSIVEFRESNEL = false;
  23960. this.FRESNEL = false;
  23961. this.NORMAL = false;
  23962. this.UV1 = false;
  23963. this.UV2 = false;
  23964. this.VERTEXCOLOR = false;
  23965. this.VERTEXALPHA = false;
  23966. this.NUM_BONE_INFLUENCERS = 0;
  23967. this.BonesPerMesh = 0;
  23968. this.INSTANCES = false;
  23969. this.GLOSSINESS = false;
  23970. this.ROUGHNESS = false;
  23971. this.EMISSIVEASILLUMINATION = false;
  23972. this.LINKEMISSIVEWITHDIFFUSE = false;
  23973. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23974. this.LIGHTMAP = false;
  23975. this.USELIGHTMAPASSHADOWMAP = false;
  23976. this.REFLECTIONMAP_3D = false;
  23977. this.REFLECTIONMAP_SPHERICAL = false;
  23978. this.REFLECTIONMAP_PLANAR = false;
  23979. this.REFLECTIONMAP_CUBIC = false;
  23980. this.REFLECTIONMAP_PROJECTION = false;
  23981. this.REFLECTIONMAP_SKYBOX = false;
  23982. this.REFLECTIONMAP_EXPLICIT = false;
  23983. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23984. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23985. this.INVERTCUBICMAP = false;
  23986. this.LOGARITHMICDEPTH = false;
  23987. this.REFRACTION = false;
  23988. this.REFRACTIONMAP_3D = false;
  23989. this.REFLECTIONOVERALPHA = false;
  23990. this.INVERTNORMALMAPX = false;
  23991. this.INVERTNORMALMAPY = false;
  23992. this.rebuild();
  23993. }
  23994. return StandardMaterialDefines;
  23995. })(BABYLON.MaterialDefines);
  23996. var StandardMaterial = (function (_super) {
  23997. __extends(StandardMaterial, _super);
  23998. function StandardMaterial(name, scene) {
  23999. var _this = this;
  24000. _super.call(this, name, scene);
  24001. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24002. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24003. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24004. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24005. this.specularPower = 64;
  24006. this.useAlphaFromDiffuseTexture = false;
  24007. this.useEmissiveAsIllumination = false;
  24008. this.linkEmissiveWithDiffuse = false;
  24009. this.useReflectionFresnelFromSpecular = false;
  24010. this.useSpecularOverAlpha = false;
  24011. this.useReflectionOverAlpha = false;
  24012. this.disableLighting = false;
  24013. this.useParallax = false;
  24014. this.useParallaxOcclusion = false;
  24015. this.parallaxScaleBias = 0.05;
  24016. this.roughness = 0;
  24017. this.indexOfRefraction = 0.98;
  24018. this.invertRefractionY = true;
  24019. this.useLightmapAsShadowmap = false;
  24020. this.useGlossinessFromSpecularMapAlpha = false;
  24021. this.maxSimultaneousLights = 4;
  24022. /**
  24023. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24024. */
  24025. this.invertNormalMapX = false;
  24026. /**
  24027. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24028. */
  24029. this.invertNormalMapY = false;
  24030. this._renderTargets = new BABYLON.SmartArray(16);
  24031. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24032. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24033. this._defines = new StandardMaterialDefines();
  24034. this._cachedDefines = new StandardMaterialDefines();
  24035. this._cachedDefines.BonesPerMesh = -1;
  24036. this.getRenderTargetTextures = function () {
  24037. _this._renderTargets.reset();
  24038. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24039. _this._renderTargets.push(_this.reflectionTexture);
  24040. }
  24041. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24042. _this._renderTargets.push(_this.refractionTexture);
  24043. }
  24044. return _this._renderTargets;
  24045. };
  24046. }
  24047. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24048. get: function () {
  24049. return this._useLogarithmicDepth;
  24050. },
  24051. set: function (value) {
  24052. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24053. },
  24054. enumerable: true,
  24055. configurable: true
  24056. });
  24057. StandardMaterial.prototype.needAlphaBlending = function () {
  24058. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24059. };
  24060. StandardMaterial.prototype.needAlphaTesting = function () {
  24061. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24062. };
  24063. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24064. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24065. };
  24066. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24067. return this.diffuseTexture;
  24068. };
  24069. // Methods
  24070. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24071. if (!mesh) {
  24072. return true;
  24073. }
  24074. if (this._defines.INSTANCES !== useInstances) {
  24075. return false;
  24076. }
  24077. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24078. return true;
  24079. }
  24080. return false;
  24081. };
  24082. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24083. if (this.isFrozen) {
  24084. if (this._wasPreviouslyReady) {
  24085. return true;
  24086. }
  24087. }
  24088. var scene = this.getScene();
  24089. if (!this.checkReadyOnEveryCall) {
  24090. if (this._renderId === scene.getRenderId()) {
  24091. if (this._checkCache(scene, mesh, useInstances)) {
  24092. return true;
  24093. }
  24094. }
  24095. }
  24096. var engine = scene.getEngine();
  24097. var needNormals = false;
  24098. var needUVs = false;
  24099. this._defines.reset();
  24100. // Textures
  24101. if (scene.texturesEnabled) {
  24102. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24103. if (!this.diffuseTexture.isReady()) {
  24104. return false;
  24105. }
  24106. else {
  24107. needUVs = true;
  24108. this._defines.DIFFUSE = true;
  24109. }
  24110. }
  24111. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24112. if (!this.ambientTexture.isReady()) {
  24113. return false;
  24114. }
  24115. else {
  24116. needUVs = true;
  24117. this._defines.AMBIENT = true;
  24118. }
  24119. }
  24120. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24121. if (!this.opacityTexture.isReady()) {
  24122. return false;
  24123. }
  24124. else {
  24125. needUVs = true;
  24126. this._defines.OPACITY = true;
  24127. if (this.opacityTexture.getAlphaFromRGB) {
  24128. this._defines.OPACITYRGB = true;
  24129. }
  24130. }
  24131. }
  24132. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24133. if (!this.reflectionTexture.isReady()) {
  24134. return false;
  24135. }
  24136. else {
  24137. needNormals = true;
  24138. this._defines.REFLECTION = true;
  24139. if (this.roughness > 0) {
  24140. this._defines.ROUGHNESS = true;
  24141. }
  24142. if (this.useReflectionOverAlpha) {
  24143. this._defines.REFLECTIONOVERALPHA = true;
  24144. }
  24145. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24146. this._defines.INVERTCUBICMAP = true;
  24147. }
  24148. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24149. switch (this.reflectionTexture.coordinatesMode) {
  24150. case BABYLON.Texture.CUBIC_MODE:
  24151. case BABYLON.Texture.INVCUBIC_MODE:
  24152. this._defines.REFLECTIONMAP_CUBIC = true;
  24153. break;
  24154. case BABYLON.Texture.EXPLICIT_MODE:
  24155. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24156. break;
  24157. case BABYLON.Texture.PLANAR_MODE:
  24158. this._defines.REFLECTIONMAP_PLANAR = true;
  24159. break;
  24160. case BABYLON.Texture.PROJECTION_MODE:
  24161. this._defines.REFLECTIONMAP_PROJECTION = true;
  24162. break;
  24163. case BABYLON.Texture.SKYBOX_MODE:
  24164. this._defines.REFLECTIONMAP_SKYBOX = true;
  24165. break;
  24166. case BABYLON.Texture.SPHERICAL_MODE:
  24167. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24168. break;
  24169. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24170. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24171. break;
  24172. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24173. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24174. break;
  24175. }
  24176. }
  24177. }
  24178. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24179. if (!this.emissiveTexture.isReady()) {
  24180. return false;
  24181. }
  24182. else {
  24183. needUVs = true;
  24184. this._defines.EMISSIVE = true;
  24185. }
  24186. }
  24187. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24188. if (!this.lightmapTexture.isReady()) {
  24189. return false;
  24190. }
  24191. else {
  24192. needUVs = true;
  24193. this._defines.LIGHTMAP = true;
  24194. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24195. }
  24196. }
  24197. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24198. if (!this.specularTexture.isReady()) {
  24199. return false;
  24200. }
  24201. else {
  24202. needUVs = true;
  24203. this._defines.SPECULAR = true;
  24204. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24205. }
  24206. }
  24207. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24208. if (!this.bumpTexture.isReady()) {
  24209. return false;
  24210. }
  24211. else {
  24212. needUVs = true;
  24213. this._defines.BUMP = true;
  24214. if (this.useParallax) {
  24215. this._defines.PARALLAX = true;
  24216. if (this.useParallaxOcclusion) {
  24217. this._defines.PARALLAXOCCLUSION = true;
  24218. }
  24219. }
  24220. if (this.invertNormalMapX) {
  24221. this._defines.INVERTNORMALMAPX = true;
  24222. }
  24223. if (this.invertNormalMapY) {
  24224. this._defines.INVERTNORMALMAPY = true;
  24225. }
  24226. }
  24227. }
  24228. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24229. if (!this.refractionTexture.isReady()) {
  24230. return false;
  24231. }
  24232. else {
  24233. needUVs = true;
  24234. this._defines.REFRACTION = true;
  24235. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24236. }
  24237. }
  24238. }
  24239. // Effect
  24240. if (scene.clipPlane) {
  24241. this._defines.CLIPPLANE = true;
  24242. }
  24243. if (engine.getAlphaTesting()) {
  24244. this._defines.ALPHATEST = true;
  24245. }
  24246. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24247. this._defines.ALPHAFROMDIFFUSE = true;
  24248. }
  24249. if (this.useEmissiveAsIllumination) {
  24250. this._defines.EMISSIVEASILLUMINATION = true;
  24251. }
  24252. if (this.linkEmissiveWithDiffuse) {
  24253. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24254. }
  24255. if (this.useLogarithmicDepth) {
  24256. this._defines.LOGARITHMICDEPTH = true;
  24257. }
  24258. // Point size
  24259. if (this.pointsCloud || scene.forcePointsCloud) {
  24260. this._defines.POINTSIZE = true;
  24261. }
  24262. // Fog
  24263. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24264. this._defines.FOG = true;
  24265. }
  24266. if (scene.lightsEnabled && !this.disableLighting) {
  24267. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24268. }
  24269. if (StandardMaterial.FresnelEnabled) {
  24270. // Fresnel
  24271. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24272. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24273. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24274. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24275. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24276. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24277. this._defines.DIFFUSEFRESNEL = true;
  24278. }
  24279. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24280. this._defines.OPACITYFRESNEL = true;
  24281. }
  24282. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24283. this._defines.REFLECTIONFRESNEL = true;
  24284. if (this.useReflectionFresnelFromSpecular) {
  24285. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24286. }
  24287. }
  24288. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24289. this._defines.REFRACTIONFRESNEL = true;
  24290. }
  24291. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24292. this._defines.EMISSIVEFRESNEL = true;
  24293. }
  24294. needNormals = true;
  24295. this._defines.FRESNEL = true;
  24296. }
  24297. }
  24298. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24299. this._defines.SPECULAROVERALPHA = true;
  24300. }
  24301. // Attribs
  24302. if (mesh) {
  24303. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24304. this._defines.NORMAL = true;
  24305. }
  24306. if (needUVs) {
  24307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24308. this._defines.UV1 = true;
  24309. }
  24310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24311. this._defines.UV2 = true;
  24312. }
  24313. }
  24314. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24315. this._defines.VERTEXCOLOR = true;
  24316. if (mesh.hasVertexAlpha) {
  24317. this._defines.VERTEXALPHA = true;
  24318. }
  24319. }
  24320. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24321. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24322. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24323. }
  24324. // Instances
  24325. if (useInstances) {
  24326. this._defines.INSTANCES = true;
  24327. }
  24328. }
  24329. // Get correct effect
  24330. if (!this._defines.isEqual(this._cachedDefines)) {
  24331. this._defines.cloneTo(this._cachedDefines);
  24332. scene.resetCachedMaterial();
  24333. // Fallbacks
  24334. var fallbacks = new BABYLON.EffectFallbacks();
  24335. if (this._defines.REFLECTION) {
  24336. fallbacks.addFallback(0, "REFLECTION");
  24337. }
  24338. if (this._defines.SPECULAR) {
  24339. fallbacks.addFallback(0, "SPECULAR");
  24340. }
  24341. if (this._defines.BUMP) {
  24342. fallbacks.addFallback(0, "BUMP");
  24343. }
  24344. if (this._defines.PARALLAX) {
  24345. fallbacks.addFallback(1, "PARALLAX");
  24346. }
  24347. if (this._defines.PARALLAXOCCLUSION) {
  24348. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24349. }
  24350. if (this._defines.SPECULAROVERALPHA) {
  24351. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24352. }
  24353. if (this._defines.FOG) {
  24354. fallbacks.addFallback(1, "FOG");
  24355. }
  24356. if (this._defines.POINTSIZE) {
  24357. fallbacks.addFallback(0, "POINTSIZE");
  24358. }
  24359. if (this._defines.LOGARITHMICDEPTH) {
  24360. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24361. }
  24362. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24363. if (this._defines.SPECULARTERM) {
  24364. fallbacks.addFallback(0, "SPECULARTERM");
  24365. }
  24366. if (this._defines.DIFFUSEFRESNEL) {
  24367. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24368. }
  24369. if (this._defines.OPACITYFRESNEL) {
  24370. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24371. }
  24372. if (this._defines.REFLECTIONFRESNEL) {
  24373. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24374. }
  24375. if (this._defines.EMISSIVEFRESNEL) {
  24376. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24377. }
  24378. if (this._defines.FRESNEL) {
  24379. fallbacks.addFallback(4, "FRESNEL");
  24380. }
  24381. //Attributes
  24382. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24383. if (this._defines.NORMAL) {
  24384. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24385. }
  24386. if (this._defines.UV1) {
  24387. attribs.push(BABYLON.VertexBuffer.UVKind);
  24388. }
  24389. if (this._defines.UV2) {
  24390. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24391. }
  24392. if (this._defines.VERTEXCOLOR) {
  24393. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24394. }
  24395. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24396. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24397. // Legacy browser patch
  24398. var shaderName = "default";
  24399. if (!scene.getEngine().getCaps().standardDerivatives) {
  24400. shaderName = "legacydefault";
  24401. }
  24402. var join = this._defines.toString();
  24403. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24404. "vFogInfos", "vFogColor", "pointSize",
  24405. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24406. "mBones",
  24407. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24408. "depthValues",
  24409. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24410. "logarithmicDepthConstant"
  24411. ];
  24412. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24413. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24414. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24415. }
  24416. if (!this._effect.isReady()) {
  24417. return false;
  24418. }
  24419. this._renderId = scene.getRenderId();
  24420. this._wasPreviouslyReady = true;
  24421. if (mesh) {
  24422. if (!mesh._materialDefines) {
  24423. mesh._materialDefines = new StandardMaterialDefines();
  24424. }
  24425. this._defines.cloneTo(mesh._materialDefines);
  24426. }
  24427. return true;
  24428. };
  24429. StandardMaterial.prototype.unbind = function () {
  24430. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24431. this._effect.setTexture("reflection2DSampler", null);
  24432. }
  24433. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24434. this._effect.setTexture("refraction2DSampler", null);
  24435. }
  24436. _super.prototype.unbind.call(this);
  24437. };
  24438. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24439. this._effect.setMatrix("world", world);
  24440. };
  24441. StandardMaterial.prototype.bind = function (world, mesh) {
  24442. var scene = this.getScene();
  24443. // Matrices
  24444. this.bindOnlyWorldMatrix(world);
  24445. // Bones
  24446. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24447. if (scene.getCachedMaterial() !== this) {
  24448. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24449. if (StandardMaterial.FresnelEnabled) {
  24450. // Fresnel
  24451. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24452. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24453. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24454. }
  24455. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24456. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24457. }
  24458. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24459. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24460. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24461. }
  24462. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24463. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24464. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24465. }
  24466. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24467. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24468. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24469. }
  24470. }
  24471. // Textures
  24472. if (scene.texturesEnabled) {
  24473. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24474. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24475. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24476. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24477. }
  24478. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24479. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24480. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24481. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24482. }
  24483. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24484. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24485. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24486. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24487. }
  24488. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24489. if (this.reflectionTexture.isCube) {
  24490. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24491. }
  24492. else {
  24493. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24494. }
  24495. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24496. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24497. }
  24498. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24499. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24500. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24501. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24502. }
  24503. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24504. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24505. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24506. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24507. }
  24508. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24509. this._effect.setTexture("specularSampler", this.specularTexture);
  24510. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24511. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24512. }
  24513. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24514. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24515. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24516. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24517. }
  24518. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24519. var depth = 1.0;
  24520. if (this.refractionTexture.isCube) {
  24521. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24522. }
  24523. else {
  24524. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24525. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24526. if (this.refractionTexture.depth) {
  24527. depth = this.refractionTexture.depth;
  24528. }
  24529. }
  24530. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24531. }
  24532. }
  24533. // Clip plane
  24534. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24535. // Point size
  24536. if (this.pointsCloud) {
  24537. this._effect.setFloat("pointSize", this.pointSize);
  24538. }
  24539. // Colors
  24540. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24541. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24542. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24543. if (this._defines.SPECULARTERM) {
  24544. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24545. }
  24546. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24547. }
  24548. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24549. // Diffuse
  24550. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24551. // Lights
  24552. if (scene.lightsEnabled && !this.disableLighting) {
  24553. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24554. }
  24555. // View
  24556. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24557. this._effect.setMatrix("view", scene.getViewMatrix());
  24558. }
  24559. // Fog
  24560. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24561. // Log. depth
  24562. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24563. }
  24564. _super.prototype.bind.call(this, world, mesh);
  24565. };
  24566. StandardMaterial.prototype.getAnimatables = function () {
  24567. var results = [];
  24568. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24569. results.push(this.diffuseTexture);
  24570. }
  24571. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24572. results.push(this.ambientTexture);
  24573. }
  24574. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24575. results.push(this.opacityTexture);
  24576. }
  24577. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24578. results.push(this.reflectionTexture);
  24579. }
  24580. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24581. results.push(this.emissiveTexture);
  24582. }
  24583. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24584. results.push(this.specularTexture);
  24585. }
  24586. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24587. results.push(this.bumpTexture);
  24588. }
  24589. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24590. results.push(this.lightmapTexture);
  24591. }
  24592. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24593. results.push(this.refractionTexture);
  24594. }
  24595. return results;
  24596. };
  24597. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24598. if (forceDisposeTextures) {
  24599. if (this.diffuseTexture) {
  24600. this.diffuseTexture.dispose();
  24601. }
  24602. if (this.ambientTexture) {
  24603. this.ambientTexture.dispose();
  24604. }
  24605. if (this.opacityTexture) {
  24606. this.opacityTexture.dispose();
  24607. }
  24608. if (this.reflectionTexture) {
  24609. this.reflectionTexture.dispose();
  24610. }
  24611. if (this.emissiveTexture) {
  24612. this.emissiveTexture.dispose();
  24613. }
  24614. if (this.specularTexture) {
  24615. this.specularTexture.dispose();
  24616. }
  24617. if (this.bumpTexture) {
  24618. this.bumpTexture.dispose();
  24619. }
  24620. if (this.lightmapTexture) {
  24621. this.lightmapTexture.dispose();
  24622. }
  24623. if (this.refractionTexture) {
  24624. this.refractionTexture.dispose();
  24625. }
  24626. }
  24627. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24628. };
  24629. StandardMaterial.prototype.clone = function (name) {
  24630. var _this = this;
  24631. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24632. };
  24633. StandardMaterial.prototype.serialize = function () {
  24634. return BABYLON.SerializationHelper.Serialize(this);
  24635. };
  24636. // Statics
  24637. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24638. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24639. };
  24640. // Flags used to enable or disable a type of texture for all Standard Materials
  24641. StandardMaterial.DiffuseTextureEnabled = true;
  24642. StandardMaterial.AmbientTextureEnabled = true;
  24643. StandardMaterial.OpacityTextureEnabled = true;
  24644. StandardMaterial.ReflectionTextureEnabled = true;
  24645. StandardMaterial.EmissiveTextureEnabled = true;
  24646. StandardMaterial.SpecularTextureEnabled = true;
  24647. StandardMaterial.BumpTextureEnabled = true;
  24648. StandardMaterial.FresnelEnabled = true;
  24649. StandardMaterial.LightmapTextureEnabled = true;
  24650. StandardMaterial.RefractionTextureEnabled = true;
  24651. __decorate([
  24652. BABYLON.serializeAsTexture()
  24653. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24654. __decorate([
  24655. BABYLON.serializeAsTexture()
  24656. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24657. __decorate([
  24658. BABYLON.serializeAsTexture()
  24659. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24660. __decorate([
  24661. BABYLON.serializeAsTexture()
  24662. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24663. __decorate([
  24664. BABYLON.serializeAsTexture()
  24665. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24666. __decorate([
  24667. BABYLON.serializeAsTexture()
  24668. ], StandardMaterial.prototype, "specularTexture", void 0);
  24669. __decorate([
  24670. BABYLON.serializeAsTexture()
  24671. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24672. __decorate([
  24673. BABYLON.serializeAsTexture()
  24674. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24675. __decorate([
  24676. BABYLON.serializeAsTexture()
  24677. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24678. __decorate([
  24679. BABYLON.serializeAsColor3("ambient")
  24680. ], StandardMaterial.prototype, "ambientColor", void 0);
  24681. __decorate([
  24682. BABYLON.serializeAsColor3("diffuse")
  24683. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24684. __decorate([
  24685. BABYLON.serializeAsColor3("specular")
  24686. ], StandardMaterial.prototype, "specularColor", void 0);
  24687. __decorate([
  24688. BABYLON.serializeAsColor3("emissive")
  24689. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24690. __decorate([
  24691. BABYLON.serialize()
  24692. ], StandardMaterial.prototype, "specularPower", void 0);
  24693. __decorate([
  24694. BABYLON.serialize()
  24695. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24696. __decorate([
  24697. BABYLON.serialize()
  24698. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24699. __decorate([
  24700. BABYLON.serialize()
  24701. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24702. __decorate([
  24703. BABYLON.serialize()
  24704. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24705. __decorate([
  24706. BABYLON.serialize()
  24707. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24708. __decorate([
  24709. BABYLON.serialize()
  24710. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24711. __decorate([
  24712. BABYLON.serialize()
  24713. ], StandardMaterial.prototype, "disableLighting", void 0);
  24714. __decorate([
  24715. BABYLON.serialize()
  24716. ], StandardMaterial.prototype, "useParallax", void 0);
  24717. __decorate([
  24718. BABYLON.serialize()
  24719. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24720. __decorate([
  24721. BABYLON.serialize()
  24722. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24723. __decorate([
  24724. BABYLON.serialize()
  24725. ], StandardMaterial.prototype, "roughness", void 0);
  24726. __decorate([
  24727. BABYLON.serialize()
  24728. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24729. __decorate([
  24730. BABYLON.serialize()
  24731. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24732. __decorate([
  24733. BABYLON.serialize()
  24734. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24735. __decorate([
  24736. BABYLON.serializeAsFresnelParameters()
  24737. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24738. __decorate([
  24739. BABYLON.serializeAsFresnelParameters()
  24740. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24741. __decorate([
  24742. BABYLON.serializeAsFresnelParameters()
  24743. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24744. __decorate([
  24745. BABYLON.serializeAsFresnelParameters()
  24746. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24747. __decorate([
  24748. BABYLON.serializeAsFresnelParameters()
  24749. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24750. __decorate([
  24751. BABYLON.serialize()
  24752. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24753. __decorate([
  24754. BABYLON.serialize()
  24755. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24756. __decorate([
  24757. BABYLON.serialize()
  24758. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24759. __decorate([
  24760. BABYLON.serialize()
  24761. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24762. __decorate([
  24763. BABYLON.serialize()
  24764. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24765. return StandardMaterial;
  24766. })(BABYLON.Material);
  24767. BABYLON.StandardMaterial = StandardMaterial;
  24768. })(BABYLON || (BABYLON = {}));
  24769. var BABYLON;
  24770. (function (BABYLON) {
  24771. var MultiMaterial = (function (_super) {
  24772. __extends(MultiMaterial, _super);
  24773. function MultiMaterial(name, scene) {
  24774. _super.call(this, name, scene, true);
  24775. this.subMaterials = new Array();
  24776. scene.multiMaterials.push(this);
  24777. }
  24778. // Properties
  24779. MultiMaterial.prototype.getSubMaterial = function (index) {
  24780. if (index < 0 || index >= this.subMaterials.length) {
  24781. return this.getScene().defaultMaterial;
  24782. }
  24783. return this.subMaterials[index];
  24784. };
  24785. // Methods
  24786. MultiMaterial.prototype.isReady = function (mesh) {
  24787. for (var index = 0; index < this.subMaterials.length; index++) {
  24788. var subMaterial = this.subMaterials[index];
  24789. if (subMaterial) {
  24790. if (!this.subMaterials[index].isReady(mesh)) {
  24791. return false;
  24792. }
  24793. }
  24794. }
  24795. return true;
  24796. };
  24797. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24798. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24799. for (var index = 0; index < this.subMaterials.length; index++) {
  24800. var subMaterial = null;
  24801. if (cloneChildren) {
  24802. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24803. }
  24804. else {
  24805. subMaterial = this.subMaterials[index];
  24806. }
  24807. newMultiMaterial.subMaterials.push(subMaterial);
  24808. }
  24809. return newMultiMaterial;
  24810. };
  24811. MultiMaterial.prototype.serialize = function () {
  24812. var serializationObject = {};
  24813. serializationObject.name = this.name;
  24814. serializationObject.id = this.id;
  24815. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24816. serializationObject.materials = [];
  24817. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24818. var subMat = this.subMaterials[matIndex];
  24819. if (subMat) {
  24820. serializationObject.materials.push(subMat.id);
  24821. }
  24822. else {
  24823. serializationObject.materials.push(null);
  24824. }
  24825. }
  24826. return serializationObject;
  24827. };
  24828. return MultiMaterial;
  24829. })(BABYLON.Material);
  24830. BABYLON.MultiMaterial = MultiMaterial;
  24831. })(BABYLON || (BABYLON = {}));
  24832. var BABYLON;
  24833. (function (BABYLON) {
  24834. var SceneLoader = (function () {
  24835. function SceneLoader() {
  24836. }
  24837. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24838. get: function () {
  24839. return 0;
  24840. },
  24841. enumerable: true,
  24842. configurable: true
  24843. });
  24844. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24845. get: function () {
  24846. return 1;
  24847. },
  24848. enumerable: true,
  24849. configurable: true
  24850. });
  24851. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24852. get: function () {
  24853. return 2;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24859. get: function () {
  24860. return 3;
  24861. },
  24862. enumerable: true,
  24863. configurable: true
  24864. });
  24865. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24866. get: function () {
  24867. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24868. },
  24869. set: function (value) {
  24870. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24876. get: function () {
  24877. return SceneLoader._ShowLoadingScreen;
  24878. },
  24879. set: function (value) {
  24880. SceneLoader._ShowLoadingScreen = value;
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. Object.defineProperty(SceneLoader, "loggingLevel", {
  24886. get: function () {
  24887. return SceneLoader._loggingLevel;
  24888. },
  24889. set: function (value) {
  24890. SceneLoader._loggingLevel = value;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24896. var dotPosition = sceneFilename.lastIndexOf(".");
  24897. var queryStringPosition = sceneFilename.indexOf("?");
  24898. if (queryStringPosition === -1) {
  24899. queryStringPosition = sceneFilename.length;
  24900. }
  24901. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24902. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24903. var plugin = this._registeredPlugins[index];
  24904. if (plugin.extensions.indexOf(extension) !== -1) {
  24905. return plugin;
  24906. }
  24907. }
  24908. return this._registeredPlugins[0];
  24909. };
  24910. // Public functions
  24911. SceneLoader.GetPluginForExtension = function (extension) {
  24912. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24913. var plugin = this._registeredPlugins[index];
  24914. if (plugin.extensions.indexOf(extension) !== -1) {
  24915. return plugin;
  24916. }
  24917. }
  24918. return null;
  24919. };
  24920. SceneLoader.RegisterPlugin = function (plugin) {
  24921. plugin.extensions = plugin.extensions.toLowerCase();
  24922. SceneLoader._registeredPlugins.push(plugin);
  24923. };
  24924. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24925. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24926. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24927. return;
  24928. }
  24929. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24930. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24931. return;
  24932. }
  24933. var loadingToken = {};
  24934. scene._addPendingData(loadingToken);
  24935. var manifestChecked = function (success) {
  24936. scene.database = database;
  24937. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24938. var importMeshFromData = function (data) {
  24939. var meshes = [];
  24940. var particleSystems = [];
  24941. var skeletons = [];
  24942. try {
  24943. if (plugin.importMesh) {
  24944. var syncedPlugin = plugin;
  24945. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24946. if (onerror) {
  24947. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24948. }
  24949. scene._removePendingData(loadingToken);
  24950. return;
  24951. }
  24952. if (onsuccess) {
  24953. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24954. onsuccess(meshes, particleSystems, skeletons);
  24955. scene._removePendingData(loadingToken);
  24956. }
  24957. }
  24958. else {
  24959. var asyncedPlugin = plugin;
  24960. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24961. if (onsuccess) {
  24962. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24963. onsuccess(meshes, particleSystems, skeletons);
  24964. scene._removePendingData(loadingToken);
  24965. }
  24966. }, function () {
  24967. if (onerror) {
  24968. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24969. }
  24970. scene._removePendingData(loadingToken);
  24971. });
  24972. }
  24973. }
  24974. catch (e) {
  24975. if (onerror) {
  24976. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24977. }
  24978. scene._removePendingData(loadingToken);
  24979. }
  24980. };
  24981. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24982. // Direct load
  24983. importMeshFromData(sceneFilename.substr(5));
  24984. return;
  24985. }
  24986. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24987. importMeshFromData(data);
  24988. }, progressCallBack, database);
  24989. };
  24990. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24991. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24992. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24993. }
  24994. else {
  24995. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24996. manifestChecked(true);
  24997. }
  24998. };
  24999. /**
  25000. * Load a scene
  25001. * @param rootUrl a string that defines the root url for scene and resources
  25002. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25003. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25004. */
  25005. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25006. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25007. };
  25008. /**
  25009. * Append a scene
  25010. * @param rootUrl a string that defines the root url for scene and resources
  25011. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25012. * @param scene is the instance of BABYLON.Scene to append to
  25013. */
  25014. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25015. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25016. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25017. return;
  25018. }
  25019. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25020. var database;
  25021. var loadingToken = {};
  25022. scene._addPendingData(loadingToken);
  25023. if (SceneLoader.ShowLoadingScreen) {
  25024. scene.getEngine().displayLoadingUI();
  25025. }
  25026. var loadSceneFromData = function (data) {
  25027. scene.database = database;
  25028. if (plugin.load) {
  25029. var syncedPlugin = plugin;
  25030. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25031. if (onerror) {
  25032. onerror(scene);
  25033. }
  25034. scene._removePendingData(loadingToken);
  25035. scene.getEngine().hideLoadingUI();
  25036. return;
  25037. }
  25038. if (onsuccess) {
  25039. onsuccess(scene);
  25040. }
  25041. scene._removePendingData(loadingToken);
  25042. }
  25043. else {
  25044. var asyncedPlugin = plugin;
  25045. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25046. if (onsuccess) {
  25047. onsuccess(scene);
  25048. }
  25049. }, function () {
  25050. if (onerror) {
  25051. onerror(scene);
  25052. }
  25053. scene._removePendingData(loadingToken);
  25054. scene.getEngine().hideLoadingUI();
  25055. });
  25056. }
  25057. if (SceneLoader.ShowLoadingScreen) {
  25058. scene.executeWhenReady(function () {
  25059. scene.getEngine().hideLoadingUI();
  25060. });
  25061. }
  25062. };
  25063. var manifestChecked = function (success) {
  25064. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25065. };
  25066. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25067. // Direct load
  25068. loadSceneFromData(sceneFilename.substr(5));
  25069. return;
  25070. }
  25071. if (rootUrl.indexOf("file:") === -1) {
  25072. if (scene.getEngine().enableOfflineSupport) {
  25073. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25074. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25075. }
  25076. else {
  25077. manifestChecked(true);
  25078. }
  25079. }
  25080. else {
  25081. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25082. }
  25083. };
  25084. // Flags
  25085. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25086. SceneLoader._ShowLoadingScreen = true;
  25087. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25088. // Members
  25089. SceneLoader._registeredPlugins = new Array();
  25090. return SceneLoader;
  25091. })();
  25092. BABYLON.SceneLoader = SceneLoader;
  25093. ;
  25094. })(BABYLON || (BABYLON = {}));
  25095. var BABYLON;
  25096. (function (BABYLON) {
  25097. var Internals;
  25098. (function (Internals) {
  25099. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25100. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25101. var parsedMaterial = parsedData.materials[index];
  25102. if (parsedMaterial.id === id) {
  25103. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25104. }
  25105. }
  25106. return null;
  25107. };
  25108. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25109. names = (names instanceof Array) ? names : [names];
  25110. for (var i in names) {
  25111. if (mesh.name === names[i]) {
  25112. hierarchyIds.push(mesh.id);
  25113. return true;
  25114. }
  25115. }
  25116. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25117. hierarchyIds.push(mesh.id);
  25118. return true;
  25119. }
  25120. return false;
  25121. };
  25122. var logOperation = function (operation, producer) {
  25123. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25124. };
  25125. BABYLON.SceneLoader.RegisterPlugin({
  25126. extensions: ".babylon",
  25127. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25131. // and avoid problems with multiple concurrent .babylon loads.
  25132. var log = "importMesh has failed JSON parse";
  25133. try {
  25134. var parsedData = JSON.parse(data);
  25135. log = "";
  25136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25137. var loadedSkeletonsIds = [];
  25138. var loadedMaterialsIds = [];
  25139. var hierarchyIds = [];
  25140. var index;
  25141. var cache;
  25142. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25143. var parsedMesh = parsedData.meshes[index];
  25144. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25145. if (meshesNames instanceof Array) {
  25146. // Remove found mesh name from list.
  25147. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25148. }
  25149. //Geometry?
  25150. if (parsedMesh.geometryId) {
  25151. //does the file contain geometries?
  25152. if (parsedData.geometries) {
  25153. //find the correct geometry and add it to the scene
  25154. var found = false;
  25155. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25156. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25157. return;
  25158. }
  25159. else {
  25160. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25161. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25162. switch (geometryType) {
  25163. case "boxes":
  25164. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25165. break;
  25166. case "spheres":
  25167. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25168. break;
  25169. case "cylinders":
  25170. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25171. break;
  25172. case "toruses":
  25173. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25174. break;
  25175. case "grounds":
  25176. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25177. break;
  25178. case "planes":
  25179. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25180. break;
  25181. case "torusKnots":
  25182. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25183. break;
  25184. case "vertexData":
  25185. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25186. break;
  25187. }
  25188. found = true;
  25189. }
  25190. });
  25191. }
  25192. });
  25193. if (!found) {
  25194. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25195. }
  25196. }
  25197. }
  25198. // Material ?
  25199. if (parsedMesh.materialId) {
  25200. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25201. if (!materialFound && parsedData.multiMaterials) {
  25202. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25203. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25204. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25205. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25206. var subMatId = parsedMultiMaterial.materials[matIndex];
  25207. loadedMaterialsIds.push(subMatId);
  25208. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25209. log += "\n\tMaterial " + mat.toString(fullDetails);
  25210. }
  25211. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25212. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25213. materialFound = true;
  25214. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25215. break;
  25216. }
  25217. }
  25218. }
  25219. if (!materialFound) {
  25220. loadedMaterialsIds.push(parsedMesh.materialId);
  25221. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25222. if (!mat) {
  25223. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25224. }
  25225. else {
  25226. log += "\n\tMaterial " + mat.toString(fullDetails);
  25227. }
  25228. }
  25229. }
  25230. // Skeleton ?
  25231. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25232. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25233. if (!skeletonAlreadyLoaded) {
  25234. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25235. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25236. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25237. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25238. skeletons.push(skeleton);
  25239. loadedSkeletonsIds.push(parsedSkeleton.id);
  25240. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25241. }
  25242. }
  25243. }
  25244. }
  25245. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25246. meshes.push(mesh);
  25247. log += "\n\tMesh " + mesh.toString(fullDetails);
  25248. }
  25249. }
  25250. // Connecting parents
  25251. var currentMesh;
  25252. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25253. currentMesh = scene.meshes[index];
  25254. if (currentMesh._waitingParentId) {
  25255. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25256. currentMesh._waitingParentId = undefined;
  25257. }
  25258. }
  25259. // freeze and compute world matrix application
  25260. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25261. currentMesh = scene.meshes[index];
  25262. if (currentMesh._waitingFreezeWorldMatrix) {
  25263. currentMesh.freezeWorldMatrix();
  25264. currentMesh._waitingFreezeWorldMatrix = undefined;
  25265. }
  25266. else {
  25267. currentMesh.computeWorldMatrix(true);
  25268. }
  25269. }
  25270. // Particles
  25271. if (parsedData.particleSystems) {
  25272. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25273. var parsedParticleSystem = parsedData.particleSystems[index];
  25274. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25275. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25276. }
  25277. }
  25278. }
  25279. return true;
  25280. }
  25281. catch (err) {
  25282. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25283. log = null;
  25284. throw err;
  25285. }
  25286. finally {
  25287. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25288. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25289. }
  25290. }
  25291. },
  25292. load: function (scene, data, rootUrl) {
  25293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25296. // and avoid problems with multiple concurrent .babylon loads.
  25297. var log = "importScene has failed JSON parse";
  25298. try {
  25299. var parsedData = JSON.parse(data);
  25300. log = "";
  25301. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25302. // Scene
  25303. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25304. scene.autoClear = parsedData.autoClear;
  25305. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25306. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25307. if (parsedData.gravity) {
  25308. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25309. }
  25310. // Fog
  25311. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25312. scene.fogMode = parsedData.fogMode;
  25313. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25314. scene.fogStart = parsedData.fogStart;
  25315. scene.fogEnd = parsedData.fogEnd;
  25316. scene.fogDensity = parsedData.fogDensity;
  25317. log += "\tFog mode for scene: ";
  25318. switch (scene.fogMode) {
  25319. // getters not compiling, so using hardcoded
  25320. case 1:
  25321. log += "exp\n";
  25322. break;
  25323. case 2:
  25324. log += "exp2\n";
  25325. break;
  25326. case 3:
  25327. log += "linear\n";
  25328. break;
  25329. }
  25330. }
  25331. //Physics
  25332. if (parsedData.physicsEnabled) {
  25333. var physicsPlugin;
  25334. if (parsedData.physicsEngine === "cannon") {
  25335. physicsPlugin = new BABYLON.CannonJSPlugin();
  25336. }
  25337. else if (parsedData.physicsEngine === "oimo") {
  25338. physicsPlugin = new BABYLON.OimoJSPlugin();
  25339. }
  25340. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25341. //else - default engine, which is currently oimo
  25342. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25343. scene.enablePhysics(physicsGravity, physicsPlugin);
  25344. }
  25345. //collisions, if defined. otherwise, default is true
  25346. if (parsedData.collisionsEnabled != undefined) {
  25347. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25348. }
  25349. scene.workerCollisions = !!parsedData.workerCollisions;
  25350. var index;
  25351. var cache;
  25352. // Lights
  25353. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25354. var parsedLight = parsedData.lights[index];
  25355. var light = BABYLON.Light.Parse(parsedLight, scene);
  25356. log += (index === 0 ? "\n\tLights:" : "");
  25357. log += "\n\t\t" + light.toString(fullDetails);
  25358. }
  25359. // Animations
  25360. if (parsedData.animations) {
  25361. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25362. var parsedAnimation = parsedData.animations[index];
  25363. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25364. scene.animations.push(animation);
  25365. log += (index === 0 ? "\n\tAnimations:" : "");
  25366. log += "\n\t\t" + animation.toString(fullDetails);
  25367. }
  25368. }
  25369. if (parsedData.autoAnimate) {
  25370. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25371. }
  25372. // Materials
  25373. if (parsedData.materials) {
  25374. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25375. var parsedMaterial = parsedData.materials[index];
  25376. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25377. log += (index === 0 ? "\n\tMaterials:" : "");
  25378. log += "\n\t\t" + mat.toString(fullDetails);
  25379. }
  25380. }
  25381. if (parsedData.multiMaterials) {
  25382. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25383. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25384. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25385. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25386. log += "\n\t\t" + mmat.toString(fullDetails);
  25387. }
  25388. }
  25389. // Skeletons
  25390. if (parsedData.skeletons) {
  25391. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25392. var parsedSkeleton = parsedData.skeletons[index];
  25393. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25394. log += (index === 0 ? "\n\tSkeletons:" : "");
  25395. log += "\n\t\t" + skeleton.toString(fullDetails);
  25396. }
  25397. }
  25398. // Geometries
  25399. var geometries = parsedData.geometries;
  25400. if (geometries) {
  25401. // Boxes
  25402. var boxes = geometries.boxes;
  25403. if (boxes) {
  25404. for (index = 0, cache = boxes.length; index < cache; index++) {
  25405. var parsedBox = boxes[index];
  25406. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25407. }
  25408. }
  25409. // Spheres
  25410. var spheres = geometries.spheres;
  25411. if (spheres) {
  25412. for (index = 0, cache = spheres.length; index < cache; index++) {
  25413. var parsedSphere = spheres[index];
  25414. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25415. }
  25416. }
  25417. // Cylinders
  25418. var cylinders = geometries.cylinders;
  25419. if (cylinders) {
  25420. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25421. var parsedCylinder = cylinders[index];
  25422. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25423. }
  25424. }
  25425. // Toruses
  25426. var toruses = geometries.toruses;
  25427. if (toruses) {
  25428. for (index = 0, cache = toruses.length; index < cache; index++) {
  25429. var parsedTorus = toruses[index];
  25430. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25431. }
  25432. }
  25433. // Grounds
  25434. var grounds = geometries.grounds;
  25435. if (grounds) {
  25436. for (index = 0, cache = grounds.length; index < cache; index++) {
  25437. var parsedGround = grounds[index];
  25438. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25439. }
  25440. }
  25441. // Planes
  25442. var planes = geometries.planes;
  25443. if (planes) {
  25444. for (index = 0, cache = planes.length; index < cache; index++) {
  25445. var parsedPlane = planes[index];
  25446. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25447. }
  25448. }
  25449. // TorusKnots
  25450. var torusKnots = geometries.torusKnots;
  25451. if (torusKnots) {
  25452. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25453. var parsedTorusKnot = torusKnots[index];
  25454. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25455. }
  25456. }
  25457. // VertexData
  25458. var vertexData = geometries.vertexData;
  25459. if (vertexData) {
  25460. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25461. var parsedVertexData = vertexData[index];
  25462. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25463. }
  25464. }
  25465. }
  25466. // Meshes
  25467. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25468. var parsedMesh = parsedData.meshes[index];
  25469. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25470. log += (index === 0 ? "\n\tMeshes:" : "");
  25471. log += "\n\t\t" + mesh.toString(fullDetails);
  25472. }
  25473. // Cameras
  25474. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25475. var parsedCamera = parsedData.cameras[index];
  25476. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25477. log += (index === 0 ? "\n\tCameras:" : "");
  25478. log += "\n\t\t" + camera.toString(fullDetails);
  25479. }
  25480. if (parsedData.activeCameraID) {
  25481. scene.setActiveCameraByID(parsedData.activeCameraID);
  25482. }
  25483. // Browsing all the graph to connect the dots
  25484. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25485. var camera = scene.cameras[index];
  25486. if (camera._waitingParentId) {
  25487. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25488. camera._waitingParentId = undefined;
  25489. }
  25490. }
  25491. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25492. var light = scene.lights[index];
  25493. if (light._waitingParentId) {
  25494. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25495. light._waitingParentId = undefined;
  25496. }
  25497. }
  25498. // Sounds
  25499. var loadedSounds = [];
  25500. var loadedSound;
  25501. if (BABYLON.AudioEngine && parsedData.sounds) {
  25502. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25503. var parsedSound = parsedData.sounds[index];
  25504. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25505. if (!parsedSound.url)
  25506. parsedSound.url = parsedSound.name;
  25507. if (!loadedSounds[parsedSound.url]) {
  25508. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25509. loadedSounds[parsedSound.url] = loadedSound;
  25510. }
  25511. else {
  25512. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25513. }
  25514. }
  25515. else {
  25516. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25517. }
  25518. }
  25519. }
  25520. loadedSounds = [];
  25521. // Connect parents & children and parse actions
  25522. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25523. var mesh = scene.meshes[index];
  25524. if (mesh._waitingParentId) {
  25525. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25526. mesh._waitingParentId = undefined;
  25527. }
  25528. if (mesh._waitingActions) {
  25529. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25530. mesh._waitingActions = undefined;
  25531. }
  25532. }
  25533. // freeze world matrix application
  25534. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25535. var currentMesh = scene.meshes[index];
  25536. if (currentMesh._waitingFreezeWorldMatrix) {
  25537. currentMesh.freezeWorldMatrix();
  25538. currentMesh._waitingFreezeWorldMatrix = undefined;
  25539. }
  25540. else {
  25541. currentMesh.computeWorldMatrix(true);
  25542. }
  25543. }
  25544. // Particles Systems
  25545. if (parsedData.particleSystems) {
  25546. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25547. var parsedParticleSystem = parsedData.particleSystems[index];
  25548. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25549. }
  25550. }
  25551. // Lens flares
  25552. if (parsedData.lensFlareSystems) {
  25553. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25554. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25555. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25556. }
  25557. }
  25558. // Shadows
  25559. if (parsedData.shadowGenerators) {
  25560. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25561. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25562. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25563. }
  25564. }
  25565. // Actions (scene)
  25566. if (parsedData.actions) {
  25567. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25568. }
  25569. // Finish
  25570. return true;
  25571. }
  25572. catch (err) {
  25573. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25574. log = null;
  25575. throw err;
  25576. }
  25577. finally {
  25578. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25579. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25580. }
  25581. }
  25582. }
  25583. });
  25584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25585. })(BABYLON || (BABYLON = {}));
  25586. var BABYLON;
  25587. (function (BABYLON) {
  25588. var SpriteManager = (function () {
  25589. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25591. this.name = name;
  25592. this.cellSize = cellSize;
  25593. this.sprites = new Array();
  25594. this.renderingGroupId = 0;
  25595. this.layerMask = 0x0FFFFFFF;
  25596. this.fogEnabled = true;
  25597. this.isPickable = false;
  25598. /**
  25599. * An event triggered when the manager is disposed.
  25600. * @type {BABYLON.Observable}
  25601. */
  25602. this.onDisposeObservable = new BABYLON.Observable();
  25603. this._vertexBuffers = {};
  25604. this._capacity = capacity;
  25605. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25606. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25607. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25608. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25609. this._scene = scene;
  25610. this._scene.spriteManagers.push(this);
  25611. var indices = [];
  25612. var index = 0;
  25613. for (var count = 0; count < capacity; count++) {
  25614. indices.push(index);
  25615. indices.push(index + 1);
  25616. indices.push(index + 2);
  25617. indices.push(index);
  25618. indices.push(index + 2);
  25619. indices.push(index + 3);
  25620. index += 4;
  25621. }
  25622. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25623. // VBO
  25624. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25625. this._vertexData = new Float32Array(capacity * 16 * 4);
  25626. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25627. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25628. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25629. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25630. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25631. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25632. this._vertexBuffers["options"] = options;
  25633. this._vertexBuffers["cellInfo"] = cellInfo;
  25634. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25635. // Effects
  25636. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25637. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25638. }
  25639. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25640. set: function (callback) {
  25641. if (this._onDisposeObserver) {
  25642. this.onDisposeObservable.remove(this._onDisposeObserver);
  25643. }
  25644. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25645. },
  25646. enumerable: true,
  25647. configurable: true
  25648. });
  25649. Object.defineProperty(SpriteManager.prototype, "texture", {
  25650. get: function () {
  25651. return this._spriteTexture;
  25652. },
  25653. set: function (value) {
  25654. this._spriteTexture = value;
  25655. },
  25656. enumerable: true,
  25657. configurable: true
  25658. });
  25659. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25660. var arrayOffset = index * 16;
  25661. if (offsetX === 0)
  25662. offsetX = this._epsilon;
  25663. else if (offsetX === 1)
  25664. offsetX = 1 - this._epsilon;
  25665. if (offsetY === 0)
  25666. offsetY = this._epsilon;
  25667. else if (offsetY === 1)
  25668. offsetY = 1 - this._epsilon;
  25669. this._vertexData[arrayOffset] = sprite.position.x;
  25670. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25671. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25672. this._vertexData[arrayOffset + 3] = sprite.angle;
  25673. this._vertexData[arrayOffset + 4] = sprite.width;
  25674. this._vertexData[arrayOffset + 5] = sprite.height;
  25675. this._vertexData[arrayOffset + 6] = offsetX;
  25676. this._vertexData[arrayOffset + 7] = offsetY;
  25677. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25678. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25679. var offset = (sprite.cellIndex / rowSize) >> 0;
  25680. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25681. this._vertexData[arrayOffset + 11] = offset;
  25682. // Color
  25683. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25684. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25685. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25686. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25687. };
  25688. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25689. var count = Math.min(this._capacity, this.sprites.length);
  25690. var min = BABYLON.Vector3.Zero();
  25691. var max = BABYLON.Vector3.Zero();
  25692. var distance = Number.MAX_VALUE;
  25693. var currentSprite;
  25694. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25695. var cameraView = camera.getViewMatrix();
  25696. for (var index = 0; index < count; index++) {
  25697. var sprite = this.sprites[index];
  25698. if (!sprite) {
  25699. continue;
  25700. }
  25701. if (predicate) {
  25702. if (!predicate(sprite)) {
  25703. continue;
  25704. }
  25705. }
  25706. else if (!sprite.isPickable) {
  25707. continue;
  25708. }
  25709. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25710. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25711. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25712. if (ray.intersectsBoxMinMax(min, max)) {
  25713. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25714. if (distance > currentDistance) {
  25715. distance = currentDistance;
  25716. currentSprite = sprite;
  25717. if (fastCheck) {
  25718. break;
  25719. }
  25720. }
  25721. }
  25722. }
  25723. if (currentSprite) {
  25724. var result = new BABYLON.PickingInfo();
  25725. result.hit = true;
  25726. result.pickedSprite = currentSprite;
  25727. result.distance = distance;
  25728. return result;
  25729. }
  25730. return null;
  25731. };
  25732. SpriteManager.prototype.render = function () {
  25733. // Check
  25734. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25735. return;
  25736. var engine = this._scene.getEngine();
  25737. var baseSize = this._spriteTexture.getBaseSize();
  25738. // Sprites
  25739. var deltaTime = engine.getDeltaTime();
  25740. var max = Math.min(this._capacity, this.sprites.length);
  25741. var rowSize = baseSize.width / this.cellSize;
  25742. var offset = 0;
  25743. for (var index = 0; index < max; index++) {
  25744. var sprite = this.sprites[index];
  25745. if (!sprite) {
  25746. continue;
  25747. }
  25748. sprite._animate(deltaTime);
  25749. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25750. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25751. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25752. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25753. }
  25754. this._buffer.update(this._vertexData);
  25755. // Render
  25756. var effect = this._effectBase;
  25757. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25758. effect = this._effectFog;
  25759. }
  25760. engine.enableEffect(effect);
  25761. var viewMatrix = this._scene.getViewMatrix();
  25762. effect.setTexture("diffuseSampler", this._spriteTexture);
  25763. effect.setMatrix("view", viewMatrix);
  25764. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25765. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25766. // Fog
  25767. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25768. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25769. effect.setColor3("vFogColor", this._scene.fogColor);
  25770. }
  25771. // VBOs
  25772. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25773. // Draw order
  25774. engine.setDepthFunctionToLessOrEqual();
  25775. effect.setBool("alphaTest", true);
  25776. engine.setColorWrite(false);
  25777. engine.draw(true, 0, max * 6);
  25778. engine.setColorWrite(true);
  25779. effect.setBool("alphaTest", false);
  25780. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25781. engine.draw(true, 0, max * 6);
  25782. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25783. };
  25784. SpriteManager.prototype.dispose = function () {
  25785. if (this._buffer) {
  25786. this._buffer.dispose();
  25787. this._buffer = null;
  25788. }
  25789. if (this._indexBuffer) {
  25790. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25791. this._indexBuffer = null;
  25792. }
  25793. if (this._spriteTexture) {
  25794. this._spriteTexture.dispose();
  25795. this._spriteTexture = null;
  25796. }
  25797. // Remove from scene
  25798. var index = this._scene.spriteManagers.indexOf(this);
  25799. this._scene.spriteManagers.splice(index, 1);
  25800. // Callback
  25801. this.onDisposeObservable.notifyObservers(this);
  25802. this.onDisposeObservable.clear();
  25803. };
  25804. return SpriteManager;
  25805. })();
  25806. BABYLON.SpriteManager = SpriteManager;
  25807. })(BABYLON || (BABYLON = {}));
  25808. var BABYLON;
  25809. (function (BABYLON) {
  25810. var Sprite = (function () {
  25811. function Sprite(name, manager) {
  25812. this.name = name;
  25813. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25814. this.width = 1.0;
  25815. this.height = 1.0;
  25816. this.angle = 0;
  25817. this.cellIndex = 0;
  25818. this.invertU = 0;
  25819. this.invertV = 0;
  25820. this.animations = new Array();
  25821. this.isPickable = false;
  25822. this._animationStarted = false;
  25823. this._loopAnimation = false;
  25824. this._fromIndex = 0;
  25825. this._toIndex = 0;
  25826. this._delay = 0;
  25827. this._direction = 1;
  25828. this._frameCount = 0;
  25829. this._time = 0;
  25830. this._manager = manager;
  25831. this._manager.sprites.push(this);
  25832. this.position = BABYLON.Vector3.Zero();
  25833. }
  25834. Object.defineProperty(Sprite.prototype, "size", {
  25835. get: function () {
  25836. return this.width;
  25837. },
  25838. set: function (value) {
  25839. this.width = value;
  25840. this.height = value;
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25846. this._fromIndex = from;
  25847. this._toIndex = to;
  25848. this._loopAnimation = loop;
  25849. this._delay = delay;
  25850. this._animationStarted = true;
  25851. this._direction = from < to ? 1 : -1;
  25852. this.cellIndex = from;
  25853. this._time = 0;
  25854. };
  25855. Sprite.prototype.stopAnimation = function () {
  25856. this._animationStarted = false;
  25857. };
  25858. Sprite.prototype._animate = function (deltaTime) {
  25859. if (!this._animationStarted)
  25860. return;
  25861. this._time += deltaTime;
  25862. if (this._time > this._delay) {
  25863. this._time = this._time % this._delay;
  25864. this.cellIndex += this._direction;
  25865. if (this.cellIndex == this._toIndex) {
  25866. if (this._loopAnimation) {
  25867. this.cellIndex = this._fromIndex;
  25868. }
  25869. else {
  25870. this._animationStarted = false;
  25871. if (this.disposeWhenFinishedAnimating) {
  25872. this.dispose();
  25873. }
  25874. }
  25875. }
  25876. }
  25877. };
  25878. Sprite.prototype.dispose = function () {
  25879. for (var i = 0; i < this._manager.sprites.length; i++) {
  25880. if (this._manager.sprites[i] == this) {
  25881. this._manager.sprites.splice(i, 1);
  25882. }
  25883. }
  25884. };
  25885. return Sprite;
  25886. })();
  25887. BABYLON.Sprite = Sprite;
  25888. })(BABYLON || (BABYLON = {}));
  25889. var BABYLON;
  25890. (function (BABYLON) {
  25891. var Layer = (function () {
  25892. function Layer(name, imgUrl, scene, isBackground, color) {
  25893. this.name = name;
  25894. this.scale = new BABYLON.Vector2(1, 1);
  25895. this.offset = new BABYLON.Vector2(0, 0);
  25896. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25897. this._vertexBuffers = {};
  25898. // Events
  25899. /**
  25900. * An event triggered when the layer is disposed.
  25901. * @type {BABYLON.Observable}
  25902. */
  25903. this.onDisposeObservable = new BABYLON.Observable();
  25904. /**
  25905. * An event triggered before rendering the scene
  25906. * @type {BABYLON.Observable}
  25907. */
  25908. this.onBeforeRenderObservable = new BABYLON.Observable();
  25909. /**
  25910. * An event triggered after rendering the scene
  25911. * @type {BABYLON.Observable}
  25912. */
  25913. this.onAfterRenderObservable = new BABYLON.Observable();
  25914. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25915. this.isBackground = isBackground === undefined ? true : isBackground;
  25916. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25917. this._scene = scene;
  25918. this._scene.layers.push(this);
  25919. var engine = scene.getEngine();
  25920. // VBO
  25921. var vertices = [];
  25922. vertices.push(1, 1);
  25923. vertices.push(-1, 1);
  25924. vertices.push(-1, -1);
  25925. vertices.push(1, -1);
  25926. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  25928. // Indices
  25929. var indices = [];
  25930. indices.push(0);
  25931. indices.push(1);
  25932. indices.push(2);
  25933. indices.push(0);
  25934. indices.push(2);
  25935. indices.push(3);
  25936. this._indexBuffer = engine.createIndexBuffer(indices);
  25937. // Effects
  25938. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25939. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25940. }
  25941. Object.defineProperty(Layer.prototype, "onDispose", {
  25942. set: function (callback) {
  25943. if (this._onDisposeObserver) {
  25944. this.onDisposeObservable.remove(this._onDisposeObserver);
  25945. }
  25946. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25952. set: function (callback) {
  25953. if (this._onBeforeRenderObserver) {
  25954. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25955. }
  25956. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25962. set: function (callback) {
  25963. if (this._onAfterRenderObserver) {
  25964. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25965. }
  25966. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25967. },
  25968. enumerable: true,
  25969. configurable: true
  25970. });
  25971. Layer.prototype.render = function () {
  25972. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25973. // Check
  25974. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25975. return;
  25976. var engine = this._scene.getEngine();
  25977. this.onBeforeRenderObservable.notifyObservers(this);
  25978. // Render
  25979. engine.enableEffect(currentEffect);
  25980. engine.setState(false);
  25981. // Texture
  25982. currentEffect.setTexture("textureSampler", this.texture);
  25983. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25984. // Color
  25985. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25986. // Scale / offset
  25987. currentEffect.setVector2("offset", this.offset);
  25988. currentEffect.setVector2("scale", this.scale);
  25989. // VBOs
  25990. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  25991. // Draw order
  25992. if (!this._alphaTestEffect) {
  25993. engine.setAlphaMode(this.alphaBlendingMode);
  25994. engine.draw(true, 0, 6);
  25995. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25996. }
  25997. else {
  25998. engine.draw(true, 0, 6);
  25999. }
  26000. this.onAfterRenderObservable.notifyObservers(this);
  26001. };
  26002. Layer.prototype.dispose = function () {
  26003. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26004. if (vertexBuffer) {
  26005. vertexBuffer.dispose();
  26006. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26007. }
  26008. if (this._indexBuffer) {
  26009. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26010. this._indexBuffer = null;
  26011. }
  26012. if (this.texture) {
  26013. this.texture.dispose();
  26014. this.texture = null;
  26015. }
  26016. // Remove from scene
  26017. var index = this._scene.layers.indexOf(this);
  26018. this._scene.layers.splice(index, 1);
  26019. // Callback
  26020. this.onDisposeObservable.notifyObservers(this);
  26021. this.onDisposeObservable.clear();
  26022. this.onAfterRenderObservable.clear();
  26023. this.onBeforeRenderObservable.clear();
  26024. };
  26025. return Layer;
  26026. })();
  26027. BABYLON.Layer = Layer;
  26028. })(BABYLON || (BABYLON = {}));
  26029. var BABYLON;
  26030. (function (BABYLON) {
  26031. var Particle = (function () {
  26032. function Particle() {
  26033. this.position = BABYLON.Vector3.Zero();
  26034. this.direction = BABYLON.Vector3.Zero();
  26035. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26036. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26037. this.lifeTime = 1.0;
  26038. this.age = 0;
  26039. this.size = 0;
  26040. this.angle = 0;
  26041. this.angularSpeed = 0;
  26042. }
  26043. Particle.prototype.copyTo = function (other) {
  26044. other.position.copyFrom(this.position);
  26045. other.direction.copyFrom(this.direction);
  26046. other.color.copyFrom(this.color);
  26047. other.colorStep.copyFrom(this.colorStep);
  26048. other.lifeTime = this.lifeTime;
  26049. other.age = this.age;
  26050. other.size = this.size;
  26051. other.angle = this.angle;
  26052. other.angularSpeed = this.angularSpeed;
  26053. };
  26054. return Particle;
  26055. })();
  26056. BABYLON.Particle = Particle;
  26057. })(BABYLON || (BABYLON = {}));
  26058. var BABYLON;
  26059. (function (BABYLON) {
  26060. var randomNumber = function (min, max) {
  26061. if (min === max) {
  26062. return (min);
  26063. }
  26064. var random = Math.random();
  26065. return ((random * (max - min)) + min);
  26066. };
  26067. var ParticleSystem = (function () {
  26068. function ParticleSystem(name, capacity, scene, customEffect) {
  26069. var _this = this;
  26070. this.name = name;
  26071. // Members
  26072. this.animations = [];
  26073. this.renderingGroupId = 0;
  26074. this.emitter = null;
  26075. this.emitRate = 10;
  26076. this.manualEmitCount = -1;
  26077. this.updateSpeed = 0.01;
  26078. this.targetStopDuration = 0;
  26079. this.disposeOnStop = false;
  26080. this.minEmitPower = 1;
  26081. this.maxEmitPower = 1;
  26082. this.minLifeTime = 1;
  26083. this.maxLifeTime = 1;
  26084. this.minSize = 1;
  26085. this.maxSize = 1;
  26086. this.minAngularSpeed = 0;
  26087. this.maxAngularSpeed = 0;
  26088. this.layerMask = 0x0FFFFFFF;
  26089. /**
  26090. * An event triggered when the system is disposed.
  26091. * @type {BABYLON.Observable}
  26092. */
  26093. this.onDisposeObservable = new BABYLON.Observable();
  26094. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26095. this.forceDepthWrite = false;
  26096. this.gravity = BABYLON.Vector3.Zero();
  26097. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26098. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26099. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26100. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26101. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26102. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26103. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26104. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26105. this.particles = new Array();
  26106. this._stockParticles = new Array();
  26107. this._newPartsExcess = 0;
  26108. this._vertexBuffers = {};
  26109. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26110. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26111. this._scaledDirection = BABYLON.Vector3.Zero();
  26112. this._scaledGravity = BABYLON.Vector3.Zero();
  26113. this._currentRenderId = -1;
  26114. this._started = false;
  26115. this._stopped = false;
  26116. this._actualFrame = 0;
  26117. this.id = name;
  26118. this._capacity = capacity;
  26119. this._scene = scene;
  26120. this._customEffect = customEffect;
  26121. scene.particleSystems.push(this);
  26122. var indices = [];
  26123. var index = 0;
  26124. for (var count = 0; count < capacity; count++) {
  26125. indices.push(index);
  26126. indices.push(index + 1);
  26127. indices.push(index + 2);
  26128. indices.push(index);
  26129. indices.push(index + 2);
  26130. indices.push(index + 3);
  26131. index += 4;
  26132. }
  26133. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26134. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26135. this._vertexData = new Float32Array(capacity * 11 * 4);
  26136. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26137. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26138. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26139. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26140. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26141. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26142. this._vertexBuffers["options"] = options;
  26143. // Default behaviors
  26144. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26145. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26146. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26147. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26148. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26149. };
  26150. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26151. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26152. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26153. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26154. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26155. };
  26156. this.updateFunction = function (particles) {
  26157. for (var index = 0; index < particles.length; index++) {
  26158. var particle = particles[index];
  26159. particle.age += _this._scaledUpdateSpeed;
  26160. if (particle.age >= particle.lifeTime) {
  26161. _this.recycleParticle(particle);
  26162. index--;
  26163. continue;
  26164. }
  26165. else {
  26166. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26167. particle.color.addInPlace(_this._scaledColorStep);
  26168. if (particle.color.a < 0)
  26169. particle.color.a = 0;
  26170. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26171. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26172. particle.position.addInPlace(_this._scaledDirection);
  26173. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26174. particle.direction.addInPlace(_this._scaledGravity);
  26175. }
  26176. }
  26177. };
  26178. }
  26179. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26180. set: function (callback) {
  26181. if (this._onDisposeObserver) {
  26182. this.onDisposeObservable.remove(this._onDisposeObserver);
  26183. }
  26184. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. ParticleSystem.prototype.recycleParticle = function (particle) {
  26190. var lastParticle = this.particles.pop();
  26191. if (lastParticle !== particle) {
  26192. lastParticle.copyTo(particle);
  26193. this._stockParticles.push(lastParticle);
  26194. }
  26195. };
  26196. ParticleSystem.prototype.getCapacity = function () {
  26197. return this._capacity;
  26198. };
  26199. ParticleSystem.prototype.isAlive = function () {
  26200. return this._alive;
  26201. };
  26202. ParticleSystem.prototype.isStarted = function () {
  26203. return this._started;
  26204. };
  26205. ParticleSystem.prototype.start = function () {
  26206. this._started = true;
  26207. this._stopped = false;
  26208. this._actualFrame = 0;
  26209. };
  26210. ParticleSystem.prototype.stop = function () {
  26211. this._stopped = true;
  26212. };
  26213. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26214. var offset = index * 11;
  26215. this._vertexData[offset] = particle.position.x;
  26216. this._vertexData[offset + 1] = particle.position.y;
  26217. this._vertexData[offset + 2] = particle.position.z;
  26218. this._vertexData[offset + 3] = particle.color.r;
  26219. this._vertexData[offset + 4] = particle.color.g;
  26220. this._vertexData[offset + 5] = particle.color.b;
  26221. this._vertexData[offset + 6] = particle.color.a;
  26222. this._vertexData[offset + 7] = particle.angle;
  26223. this._vertexData[offset + 8] = particle.size;
  26224. this._vertexData[offset + 9] = offsetX;
  26225. this._vertexData[offset + 10] = offsetY;
  26226. };
  26227. ParticleSystem.prototype._update = function (newParticles) {
  26228. // Update current
  26229. this._alive = this.particles.length > 0;
  26230. this.updateFunction(this.particles);
  26231. // Add new ones
  26232. var worldMatrix;
  26233. if (this.emitter.position) {
  26234. worldMatrix = this.emitter.getWorldMatrix();
  26235. }
  26236. else {
  26237. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26238. }
  26239. var particle;
  26240. for (var index = 0; index < newParticles; index++) {
  26241. if (this.particles.length === this._capacity) {
  26242. break;
  26243. }
  26244. if (this._stockParticles.length !== 0) {
  26245. particle = this._stockParticles.pop();
  26246. particle.age = 0;
  26247. }
  26248. else {
  26249. particle = new BABYLON.Particle();
  26250. }
  26251. this.particles.push(particle);
  26252. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26253. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26254. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26255. particle.size = randomNumber(this.minSize, this.maxSize);
  26256. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26257. this.startPositionFunction(worldMatrix, particle.position, particle);
  26258. var step = randomNumber(0, 1.0);
  26259. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26260. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26261. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26262. }
  26263. };
  26264. ParticleSystem.prototype._getEffect = function () {
  26265. if (this._customEffect) {
  26266. return this._customEffect;
  26267. }
  26268. ;
  26269. var defines = [];
  26270. if (this._scene.clipPlane) {
  26271. defines.push("#define CLIPPLANE");
  26272. }
  26273. // Effect
  26274. var join = defines.join("\n");
  26275. if (this._cachedDefines !== join) {
  26276. this._cachedDefines = join;
  26277. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26278. }
  26279. return this._effect;
  26280. };
  26281. ParticleSystem.prototype.animate = function () {
  26282. if (!this._started)
  26283. return;
  26284. var effect = this._getEffect();
  26285. // Check
  26286. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26287. return;
  26288. if (this._currentRenderId === this._scene.getRenderId()) {
  26289. return;
  26290. }
  26291. this._currentRenderId = this._scene.getRenderId();
  26292. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26293. // determine the number of particles we need to create
  26294. var newParticles;
  26295. if (this.manualEmitCount > -1) {
  26296. newParticles = this.manualEmitCount;
  26297. this._newPartsExcess = 0;
  26298. this.manualEmitCount = 0;
  26299. }
  26300. else {
  26301. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26302. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26303. }
  26304. if (this._newPartsExcess > 1.0) {
  26305. newParticles += this._newPartsExcess >> 0;
  26306. this._newPartsExcess -= this._newPartsExcess >> 0;
  26307. }
  26308. this._alive = false;
  26309. if (!this._stopped) {
  26310. this._actualFrame += this._scaledUpdateSpeed;
  26311. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26312. this.stop();
  26313. }
  26314. else {
  26315. newParticles = 0;
  26316. }
  26317. this._update(newParticles);
  26318. // Stopped?
  26319. if (this._stopped) {
  26320. if (!this._alive) {
  26321. this._started = false;
  26322. if (this.disposeOnStop) {
  26323. this._scene._toBeDisposed.push(this);
  26324. }
  26325. }
  26326. }
  26327. // Update VBO
  26328. var offset = 0;
  26329. for (var index = 0; index < this.particles.length; index++) {
  26330. var particle = this.particles[index];
  26331. this._appendParticleVertex(offset++, particle, 0, 0);
  26332. this._appendParticleVertex(offset++, particle, 1, 0);
  26333. this._appendParticleVertex(offset++, particle, 1, 1);
  26334. this._appendParticleVertex(offset++, particle, 0, 1);
  26335. }
  26336. this._vertexBuffer.update(this._vertexData);
  26337. };
  26338. ParticleSystem.prototype.render = function () {
  26339. var effect = this._getEffect();
  26340. // Check
  26341. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26342. return 0;
  26343. var engine = this._scene.getEngine();
  26344. // Render
  26345. engine.enableEffect(effect);
  26346. engine.setState(false);
  26347. var viewMatrix = this._scene.getViewMatrix();
  26348. effect.setTexture("diffuseSampler", this.particleTexture);
  26349. effect.setMatrix("view", viewMatrix);
  26350. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26351. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26352. if (this._scene.clipPlane) {
  26353. var clipPlane = this._scene.clipPlane;
  26354. var invView = viewMatrix.clone();
  26355. invView.invert();
  26356. effect.setMatrix("invView", invView);
  26357. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26358. }
  26359. // VBOs
  26360. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26361. // Draw order
  26362. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26363. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26364. }
  26365. else {
  26366. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26367. }
  26368. if (this.forceDepthWrite) {
  26369. engine.setDepthWrite(true);
  26370. }
  26371. engine.draw(true, 0, this.particles.length * 6);
  26372. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26373. return this.particles.length;
  26374. };
  26375. ParticleSystem.prototype.dispose = function () {
  26376. if (this._vertexBuffer) {
  26377. this._vertexBuffer.dispose();
  26378. this._vertexBuffer = null;
  26379. }
  26380. if (this._indexBuffer) {
  26381. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26382. this._indexBuffer = null;
  26383. }
  26384. if (this.particleTexture) {
  26385. this.particleTexture.dispose();
  26386. this.particleTexture = null;
  26387. }
  26388. // Remove from scene
  26389. var index = this._scene.particleSystems.indexOf(this);
  26390. this._scene.particleSystems.splice(index, 1);
  26391. // Callback
  26392. this.onDisposeObservable.notifyObservers(this);
  26393. this.onDisposeObservable.clear();
  26394. };
  26395. // Clone
  26396. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26397. var result = new ParticleSystem(name, this._capacity, this._scene);
  26398. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26399. if (newEmitter === undefined) {
  26400. newEmitter = this.emitter;
  26401. }
  26402. result.emitter = newEmitter;
  26403. if (this.particleTexture) {
  26404. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26405. }
  26406. result.start();
  26407. return result;
  26408. };
  26409. ParticleSystem.prototype.serialize = function () {
  26410. var serializationObject = {};
  26411. serializationObject.name = this.name;
  26412. serializationObject.id = this.id;
  26413. // Emitter
  26414. if (this.emitter.position) {
  26415. serializationObject.emitterId = this.emitter.id;
  26416. }
  26417. else {
  26418. serializationObject.emitter = this.emitter.asArray();
  26419. }
  26420. serializationObject.capacity = this.getCapacity();
  26421. if (this.particleTexture) {
  26422. serializationObject.textureName = this.particleTexture.name;
  26423. }
  26424. // Animations
  26425. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26426. // Particle system
  26427. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26428. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26429. serializationObject.minSize = this.minSize;
  26430. serializationObject.maxSize = this.maxSize;
  26431. serializationObject.minEmitPower = this.minEmitPower;
  26432. serializationObject.maxEmitPower = this.maxEmitPower;
  26433. serializationObject.minLifeTime = this.minLifeTime;
  26434. serializationObject.maxLifeTime = this.maxLifeTime;
  26435. serializationObject.emitRate = this.emitRate;
  26436. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26437. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26438. serializationObject.gravity = this.gravity.asArray();
  26439. serializationObject.direction1 = this.direction1.asArray();
  26440. serializationObject.direction2 = this.direction2.asArray();
  26441. serializationObject.color1 = this.color1.asArray();
  26442. serializationObject.color2 = this.color2.asArray();
  26443. serializationObject.colorDead = this.colorDead.asArray();
  26444. serializationObject.updateSpeed = this.updateSpeed;
  26445. serializationObject.targetStopDuration = this.targetStopDuration;
  26446. serializationObject.textureMask = this.textureMask.asArray();
  26447. serializationObject.blendMode = this.blendMode;
  26448. return serializationObject;
  26449. };
  26450. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26451. var name = parsedParticleSystem.name;
  26452. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26453. if (parsedParticleSystem.id) {
  26454. particleSystem.id = parsedParticleSystem.id;
  26455. }
  26456. // Texture
  26457. if (parsedParticleSystem.textureName) {
  26458. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26459. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26460. }
  26461. // Emitter
  26462. if (parsedParticleSystem.emitterId) {
  26463. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26464. }
  26465. else {
  26466. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26467. }
  26468. // Animations
  26469. if (parsedParticleSystem.animations) {
  26470. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26471. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26472. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26473. }
  26474. }
  26475. if (parsedParticleSystem.autoAnimate) {
  26476. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26477. }
  26478. // Particle system
  26479. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26480. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26481. particleSystem.minSize = parsedParticleSystem.minSize;
  26482. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26483. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26484. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26485. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26486. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26487. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26488. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26489. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26490. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26491. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26492. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26493. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26494. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26495. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26496. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26497. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26498. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26499. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26500. if (!parsedParticleSystem.preventAutoStart) {
  26501. particleSystem.start();
  26502. }
  26503. return particleSystem;
  26504. };
  26505. // Statics
  26506. ParticleSystem.BLENDMODE_ONEONE = 0;
  26507. ParticleSystem.BLENDMODE_STANDARD = 1;
  26508. return ParticleSystem;
  26509. })();
  26510. BABYLON.ParticleSystem = ParticleSystem;
  26511. })(BABYLON || (BABYLON = {}));
  26512. var BABYLON;
  26513. (function (BABYLON) {
  26514. var AnimationRange = (function () {
  26515. function AnimationRange(name, from, to) {
  26516. this.name = name;
  26517. this.from = from;
  26518. this.to = to;
  26519. }
  26520. AnimationRange.prototype.clone = function () {
  26521. return new AnimationRange(this.name, this.from, this.to);
  26522. };
  26523. return AnimationRange;
  26524. })();
  26525. BABYLON.AnimationRange = AnimationRange;
  26526. /**
  26527. * Composed of a frame, and an action function
  26528. */
  26529. var AnimationEvent = (function () {
  26530. function AnimationEvent(frame, action, onlyOnce) {
  26531. this.frame = frame;
  26532. this.action = action;
  26533. this.onlyOnce = onlyOnce;
  26534. this.isDone = false;
  26535. }
  26536. return AnimationEvent;
  26537. })();
  26538. BABYLON.AnimationEvent = AnimationEvent;
  26539. var PathCursor = (function () {
  26540. function PathCursor(path) {
  26541. this.path = path;
  26542. this._onchange = new Array();
  26543. this.value = 0;
  26544. this.animations = new Array();
  26545. }
  26546. PathCursor.prototype.getPoint = function () {
  26547. var point = this.path.getPointAtLengthPosition(this.value);
  26548. return new BABYLON.Vector3(point.x, 0, point.y);
  26549. };
  26550. PathCursor.prototype.moveAhead = function (step) {
  26551. if (step === void 0) { step = 0.002; }
  26552. this.move(step);
  26553. return this;
  26554. };
  26555. PathCursor.prototype.moveBack = function (step) {
  26556. if (step === void 0) { step = 0.002; }
  26557. this.move(-step);
  26558. return this;
  26559. };
  26560. PathCursor.prototype.move = function (step) {
  26561. if (Math.abs(step) > 1) {
  26562. throw "step size should be less than 1.";
  26563. }
  26564. this.value += step;
  26565. this.ensureLimits();
  26566. this.raiseOnChange();
  26567. return this;
  26568. };
  26569. PathCursor.prototype.ensureLimits = function () {
  26570. while (this.value > 1) {
  26571. this.value -= 1;
  26572. }
  26573. while (this.value < 0) {
  26574. this.value += 1;
  26575. }
  26576. return this;
  26577. };
  26578. // used by animation engine
  26579. PathCursor.prototype.markAsDirty = function (propertyName) {
  26580. this.ensureLimits();
  26581. this.raiseOnChange();
  26582. return this;
  26583. };
  26584. PathCursor.prototype.raiseOnChange = function () {
  26585. var _this = this;
  26586. this._onchange.forEach(function (f) { return f(_this); });
  26587. return this;
  26588. };
  26589. PathCursor.prototype.onchange = function (f) {
  26590. this._onchange.push(f);
  26591. return this;
  26592. };
  26593. return PathCursor;
  26594. })();
  26595. BABYLON.PathCursor = PathCursor;
  26596. var Animation = (function () {
  26597. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26598. this.name = name;
  26599. this.targetProperty = targetProperty;
  26600. this.framePerSecond = framePerSecond;
  26601. this.dataType = dataType;
  26602. this.loopMode = loopMode;
  26603. this.enableBlending = enableBlending;
  26604. this._offsetsCache = {};
  26605. this._highLimitsCache = {};
  26606. this._stopped = false;
  26607. this._blendingFactor = 0;
  26608. // The set of event that will be linked to this animation
  26609. this._events = new Array();
  26610. this.allowMatricesInterpolation = false;
  26611. this.blendingSpeed = 0.01;
  26612. this._ranges = {};
  26613. this.targetPropertyPath = targetProperty.split(".");
  26614. this.dataType = dataType;
  26615. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26616. }
  26617. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26618. var dataType = undefined;
  26619. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26620. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26621. }
  26622. else if (from instanceof BABYLON.Quaternion) {
  26623. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26624. }
  26625. else if (from instanceof BABYLON.Vector3) {
  26626. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26627. }
  26628. else if (from instanceof BABYLON.Vector2) {
  26629. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26630. }
  26631. else if (from instanceof BABYLON.Color3) {
  26632. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26633. }
  26634. else if (from instanceof BABYLON.Size) {
  26635. dataType = Animation.ANIMATIONTYPE_SIZE;
  26636. }
  26637. if (dataType == undefined) {
  26638. return null;
  26639. }
  26640. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26641. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26642. animation.setKeys(keys);
  26643. if (easingFunction !== undefined) {
  26644. animation.setEasingFunction(easingFunction);
  26645. }
  26646. return animation;
  26647. };
  26648. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26649. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26650. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26651. };
  26652. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26653. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26654. node.animations.push(animation);
  26655. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26656. };
  26657. // Methods
  26658. /**
  26659. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26660. */
  26661. Animation.prototype.toString = function (fullDetails) {
  26662. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26663. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26664. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26665. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26666. if (fullDetails) {
  26667. ret += ", Ranges: {";
  26668. var first = true;
  26669. for (var name in this._ranges) {
  26670. if (first) {
  26671. ret += ", ";
  26672. first = false;
  26673. }
  26674. ret += name;
  26675. }
  26676. ret += "}";
  26677. }
  26678. return ret;
  26679. };
  26680. /**
  26681. * Add an event to this animation.
  26682. */
  26683. Animation.prototype.addEvent = function (event) {
  26684. this._events.push(event);
  26685. };
  26686. /**
  26687. * Remove all events found at the given frame
  26688. * @param frame
  26689. */
  26690. Animation.prototype.removeEvents = function (frame) {
  26691. for (var index = 0; index < this._events.length; index++) {
  26692. if (this._events[index].frame === frame) {
  26693. this._events.splice(index, 1);
  26694. index--;
  26695. }
  26696. }
  26697. };
  26698. Animation.prototype.createRange = function (name, from, to) {
  26699. // check name not already in use; could happen for bones after serialized
  26700. if (!this._ranges[name]) {
  26701. this._ranges[name] = new AnimationRange(name, from, to);
  26702. }
  26703. };
  26704. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26705. if (deleteFrames === void 0) { deleteFrames = true; }
  26706. if (this._ranges[name]) {
  26707. if (deleteFrames) {
  26708. var from = this._ranges[name].from;
  26709. var to = this._ranges[name].to;
  26710. // this loop MUST go high to low for multiple splices to work
  26711. for (var key = this._keys.length - 1; key >= 0; key--) {
  26712. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26713. this._keys.splice(key, 1);
  26714. }
  26715. }
  26716. }
  26717. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26718. }
  26719. };
  26720. Animation.prototype.getRange = function (name) {
  26721. return this._ranges[name];
  26722. };
  26723. Animation.prototype.reset = function () {
  26724. this._offsetsCache = {};
  26725. this._highLimitsCache = {};
  26726. this.currentFrame = 0;
  26727. this._blendingFactor = 0;
  26728. this._originalBlendValue = null;
  26729. };
  26730. Animation.prototype.isStopped = function () {
  26731. return this._stopped;
  26732. };
  26733. Animation.prototype.getKeys = function () {
  26734. return this._keys;
  26735. };
  26736. Animation.prototype.getHighestFrame = function () {
  26737. var ret = 0;
  26738. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26739. if (ret < this._keys[key].frame) {
  26740. ret = this._keys[key].frame;
  26741. }
  26742. }
  26743. return ret;
  26744. };
  26745. Animation.prototype.getEasingFunction = function () {
  26746. return this._easingFunction;
  26747. };
  26748. Animation.prototype.setEasingFunction = function (easingFunction) {
  26749. this._easingFunction = easingFunction;
  26750. };
  26751. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26752. return startValue + (endValue - startValue) * gradient;
  26753. };
  26754. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26755. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26756. };
  26757. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26758. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26759. };
  26760. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26761. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26762. };
  26763. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26764. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26765. };
  26766. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26767. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26768. };
  26769. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26770. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26771. };
  26772. Animation.prototype.clone = function () {
  26773. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26774. if (this._keys) {
  26775. clone.setKeys(this._keys);
  26776. }
  26777. if (this._ranges) {
  26778. clone._ranges = {};
  26779. for (var name in this._ranges) {
  26780. clone._ranges[name] = this._ranges[name].clone();
  26781. }
  26782. }
  26783. return clone;
  26784. };
  26785. Animation.prototype.setKeys = function (values) {
  26786. this._keys = values.slice(0);
  26787. this._offsetsCache = {};
  26788. this._highLimitsCache = {};
  26789. };
  26790. Animation.prototype._getKeyValue = function (value) {
  26791. if (typeof value === "function") {
  26792. return value();
  26793. }
  26794. return value;
  26795. };
  26796. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26797. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26798. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26799. }
  26800. this.currentFrame = currentFrame;
  26801. // Try to get a hash to find the right key
  26802. 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));
  26803. if (this._keys[startKey].frame >= currentFrame) {
  26804. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26805. startKey--;
  26806. }
  26807. }
  26808. for (var key = startKey; key < this._keys.length; key++) {
  26809. if (this._keys[key + 1].frame >= currentFrame) {
  26810. var startValue = this._getKeyValue(this._keys[key].value);
  26811. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26812. // gradient : percent of currentFrame between the frame inf and the frame sup
  26813. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26814. // check for easingFunction and correction of gradient
  26815. if (this._easingFunction != null) {
  26816. gradient = this._easingFunction.ease(gradient);
  26817. }
  26818. switch (this.dataType) {
  26819. // Float
  26820. case Animation.ANIMATIONTYPE_FLOAT:
  26821. switch (loopMode) {
  26822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26824. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26826. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26827. }
  26828. break;
  26829. // Quaternion
  26830. case Animation.ANIMATIONTYPE_QUATERNION:
  26831. var quaternion = null;
  26832. switch (loopMode) {
  26833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26835. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26836. break;
  26837. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26838. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26839. break;
  26840. }
  26841. return quaternion;
  26842. // Vector3
  26843. case Animation.ANIMATIONTYPE_VECTOR3:
  26844. switch (loopMode) {
  26845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26847. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26849. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26850. }
  26851. // Vector2
  26852. case Animation.ANIMATIONTYPE_VECTOR2:
  26853. switch (loopMode) {
  26854. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26855. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26856. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26857. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26858. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26859. }
  26860. // Size
  26861. case Animation.ANIMATIONTYPE_SIZE:
  26862. switch (loopMode) {
  26863. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26864. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26865. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26866. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26867. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26868. }
  26869. // Color3
  26870. case Animation.ANIMATIONTYPE_COLOR3:
  26871. switch (loopMode) {
  26872. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26873. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26874. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26875. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26876. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26877. }
  26878. // Matrix
  26879. case Animation.ANIMATIONTYPE_MATRIX:
  26880. switch (loopMode) {
  26881. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26882. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26883. if (this.allowMatricesInterpolation) {
  26884. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26885. }
  26886. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26887. return startValue;
  26888. }
  26889. default:
  26890. break;
  26891. }
  26892. break;
  26893. }
  26894. }
  26895. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26896. };
  26897. Animation.prototype.setValue = function (currentValue, blend) {
  26898. if (blend === void 0) { blend = false; }
  26899. // Set value
  26900. var path;
  26901. var destination;
  26902. if (this.targetPropertyPath.length > 1) {
  26903. var property = this._target[this.targetPropertyPath[0]];
  26904. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26905. property = property[this.targetPropertyPath[index]];
  26906. }
  26907. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26908. destination = property;
  26909. }
  26910. else {
  26911. path = this.targetPropertyPath[0];
  26912. destination = this._target;
  26913. }
  26914. // Blending
  26915. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26916. if (!this._originalBlendValue) {
  26917. if (destination[path].clone) {
  26918. this._originalBlendValue = destination[path].clone();
  26919. }
  26920. else {
  26921. this._originalBlendValue = destination[path];
  26922. }
  26923. }
  26924. if (this._originalBlendValue.prototype) {
  26925. if (this._originalBlendValue.prototype.Lerp) {
  26926. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26927. }
  26928. else {
  26929. destination[path] = currentValue;
  26930. }
  26931. }
  26932. else if (this._originalBlendValue.m) {
  26933. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26934. }
  26935. else {
  26936. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26937. }
  26938. this._blendingFactor += this.blendingSpeed;
  26939. }
  26940. else {
  26941. destination[path] = currentValue;
  26942. }
  26943. if (this._target.markAsDirty) {
  26944. this._target.markAsDirty(this.targetProperty);
  26945. }
  26946. };
  26947. Animation.prototype.goToFrame = function (frame) {
  26948. if (frame < this._keys[0].frame) {
  26949. frame = this._keys[0].frame;
  26950. }
  26951. else if (frame > this._keys[this._keys.length - 1].frame) {
  26952. frame = this._keys[this._keys.length - 1].frame;
  26953. }
  26954. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26955. this.setValue(currentValue);
  26956. };
  26957. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26958. if (blend === void 0) { blend = false; }
  26959. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26960. this._stopped = true;
  26961. return false;
  26962. }
  26963. var returnValue = true;
  26964. // Adding a start key at frame 0 if missing
  26965. if (this._keys[0].frame !== 0) {
  26966. var newKey = { frame: 0, value: this._keys[0].value };
  26967. this._keys.splice(0, 0, newKey);
  26968. }
  26969. // Check limits
  26970. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26971. from = this._keys[0].frame;
  26972. }
  26973. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26974. to = this._keys[this._keys.length - 1].frame;
  26975. }
  26976. // Compute ratio
  26977. var range = to - from;
  26978. var offsetValue;
  26979. // ratio represents the frame delta between from and to
  26980. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26981. var highLimitValue = 0;
  26982. if (ratio > range && !loop) {
  26983. returnValue = false;
  26984. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26985. }
  26986. else {
  26987. // Get max value if required
  26988. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26989. var keyOffset = to.toString() + from.toString();
  26990. if (!this._offsetsCache[keyOffset]) {
  26991. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26992. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26993. switch (this.dataType) {
  26994. // Float
  26995. case Animation.ANIMATIONTYPE_FLOAT:
  26996. this._offsetsCache[keyOffset] = toValue - fromValue;
  26997. break;
  26998. // Quaternion
  26999. case Animation.ANIMATIONTYPE_QUATERNION:
  27000. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27001. break;
  27002. // Vector3
  27003. case Animation.ANIMATIONTYPE_VECTOR3:
  27004. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27005. // Vector2
  27006. case Animation.ANIMATIONTYPE_VECTOR2:
  27007. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27008. // Size
  27009. case Animation.ANIMATIONTYPE_SIZE:
  27010. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27011. // Color3
  27012. case Animation.ANIMATIONTYPE_COLOR3:
  27013. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27014. default:
  27015. break;
  27016. }
  27017. this._highLimitsCache[keyOffset] = toValue;
  27018. }
  27019. highLimitValue = this._highLimitsCache[keyOffset];
  27020. offsetValue = this._offsetsCache[keyOffset];
  27021. }
  27022. }
  27023. if (offsetValue === undefined) {
  27024. switch (this.dataType) {
  27025. // Float
  27026. case Animation.ANIMATIONTYPE_FLOAT:
  27027. offsetValue = 0;
  27028. break;
  27029. // Quaternion
  27030. case Animation.ANIMATIONTYPE_QUATERNION:
  27031. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27032. break;
  27033. // Vector3
  27034. case Animation.ANIMATIONTYPE_VECTOR3:
  27035. offsetValue = BABYLON.Vector3.Zero();
  27036. break;
  27037. // Vector2
  27038. case Animation.ANIMATIONTYPE_VECTOR2:
  27039. offsetValue = BABYLON.Vector2.Zero();
  27040. break;
  27041. // Size
  27042. case Animation.ANIMATIONTYPE_SIZE:
  27043. offsetValue = BABYLON.Size.Zero();
  27044. break;
  27045. // Color3
  27046. case Animation.ANIMATIONTYPE_COLOR3:
  27047. offsetValue = BABYLON.Color3.Black();
  27048. }
  27049. }
  27050. // Compute value
  27051. var repeatCount = (ratio / range) >> 0;
  27052. var currentFrame = returnValue ? from + ratio % range : to;
  27053. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27054. // Set value
  27055. this.setValue(currentValue);
  27056. // Check events
  27057. for (var index = 0; index < this._events.length; index++) {
  27058. if (currentFrame >= this._events[index].frame) {
  27059. var event = this._events[index];
  27060. if (!event.isDone) {
  27061. // If event should be done only once, remove it.
  27062. if (event.onlyOnce) {
  27063. this._events.splice(index, 1);
  27064. index--;
  27065. }
  27066. event.isDone = true;
  27067. event.action();
  27068. } // Don't do anything if the event has already be done.
  27069. }
  27070. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27071. // reset event, the animation is looping
  27072. this._events[index].isDone = false;
  27073. }
  27074. }
  27075. if (!returnValue) {
  27076. this._stopped = true;
  27077. }
  27078. return returnValue;
  27079. };
  27080. Animation.prototype.serialize = function () {
  27081. var serializationObject = {};
  27082. serializationObject.name = this.name;
  27083. serializationObject.property = this.targetProperty;
  27084. serializationObject.framePerSecond = this.framePerSecond;
  27085. serializationObject.dataType = this.dataType;
  27086. serializationObject.loopBehavior = this.loopMode;
  27087. var dataType = this.dataType;
  27088. serializationObject.keys = [];
  27089. var keys = this.getKeys();
  27090. for (var index = 0; index < keys.length; index++) {
  27091. var animationKey = keys[index];
  27092. var key = {};
  27093. key.frame = animationKey.frame;
  27094. switch (dataType) {
  27095. case Animation.ANIMATIONTYPE_FLOAT:
  27096. key.values = [animationKey.value];
  27097. break;
  27098. case Animation.ANIMATIONTYPE_QUATERNION:
  27099. case Animation.ANIMATIONTYPE_MATRIX:
  27100. case Animation.ANIMATIONTYPE_VECTOR3:
  27101. case Animation.ANIMATIONTYPE_COLOR3:
  27102. key.values = animationKey.value.asArray();
  27103. break;
  27104. }
  27105. serializationObject.keys.push(key);
  27106. }
  27107. serializationObject.ranges = [];
  27108. for (var name in this._ranges) {
  27109. var range = {};
  27110. range.name = name;
  27111. range.from = this._ranges[name].from;
  27112. range.to = this._ranges[name].to;
  27113. serializationObject.ranges.push(range);
  27114. }
  27115. return serializationObject;
  27116. };
  27117. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27118. get: function () {
  27119. return Animation._ANIMATIONTYPE_FLOAT;
  27120. },
  27121. enumerable: true,
  27122. configurable: true
  27123. });
  27124. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27125. get: function () {
  27126. return Animation._ANIMATIONTYPE_VECTOR3;
  27127. },
  27128. enumerable: true,
  27129. configurable: true
  27130. });
  27131. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27132. get: function () {
  27133. return Animation._ANIMATIONTYPE_VECTOR2;
  27134. },
  27135. enumerable: true,
  27136. configurable: true
  27137. });
  27138. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27139. get: function () {
  27140. return Animation._ANIMATIONTYPE_SIZE;
  27141. },
  27142. enumerable: true,
  27143. configurable: true
  27144. });
  27145. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27146. get: function () {
  27147. return Animation._ANIMATIONTYPE_QUATERNION;
  27148. },
  27149. enumerable: true,
  27150. configurable: true
  27151. });
  27152. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27153. get: function () {
  27154. return Animation._ANIMATIONTYPE_MATRIX;
  27155. },
  27156. enumerable: true,
  27157. configurable: true
  27158. });
  27159. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27160. get: function () {
  27161. return Animation._ANIMATIONTYPE_COLOR3;
  27162. },
  27163. enumerable: true,
  27164. configurable: true
  27165. });
  27166. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27167. get: function () {
  27168. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27169. },
  27170. enumerable: true,
  27171. configurable: true
  27172. });
  27173. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27174. get: function () {
  27175. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27176. },
  27177. enumerable: true,
  27178. configurable: true
  27179. });
  27180. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27181. get: function () {
  27182. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27183. },
  27184. enumerable: true,
  27185. configurable: true
  27186. });
  27187. Animation.Parse = function (parsedAnimation) {
  27188. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27189. var dataType = parsedAnimation.dataType;
  27190. var keys = [];
  27191. var data;
  27192. var index;
  27193. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27194. var key = parsedAnimation.keys[index];
  27195. switch (dataType) {
  27196. case Animation.ANIMATIONTYPE_FLOAT:
  27197. data = key.values[0];
  27198. break;
  27199. case Animation.ANIMATIONTYPE_QUATERNION:
  27200. data = BABYLON.Quaternion.FromArray(key.values);
  27201. break;
  27202. case Animation.ANIMATIONTYPE_MATRIX:
  27203. data = BABYLON.Matrix.FromArray(key.values);
  27204. break;
  27205. case Animation.ANIMATIONTYPE_COLOR3:
  27206. data = BABYLON.Color3.FromArray(key.values);
  27207. break;
  27208. case Animation.ANIMATIONTYPE_VECTOR3:
  27209. default:
  27210. data = BABYLON.Vector3.FromArray(key.values);
  27211. break;
  27212. }
  27213. keys.push({
  27214. frame: key.frame,
  27215. value: data
  27216. });
  27217. }
  27218. animation.setKeys(keys);
  27219. if (parsedAnimation.ranges) {
  27220. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27221. data = parsedAnimation.ranges[index];
  27222. animation.createRange(data.name, data.from, data.to);
  27223. }
  27224. }
  27225. return animation;
  27226. };
  27227. Animation.AppendSerializedAnimations = function (source, destination) {
  27228. if (source.animations) {
  27229. destination.animations = [];
  27230. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27231. var animation = source.animations[animationIndex];
  27232. destination.animations.push(animation.serialize());
  27233. }
  27234. }
  27235. };
  27236. // Statics
  27237. Animation._ANIMATIONTYPE_FLOAT = 0;
  27238. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27239. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27240. Animation._ANIMATIONTYPE_MATRIX = 3;
  27241. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27242. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27243. Animation._ANIMATIONTYPE_SIZE = 6;
  27244. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27245. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27246. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27247. return Animation;
  27248. })();
  27249. BABYLON.Animation = Animation;
  27250. })(BABYLON || (BABYLON = {}));
  27251. var BABYLON;
  27252. (function (BABYLON) {
  27253. var Animatable = (function () {
  27254. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27255. if (fromFrame === void 0) { fromFrame = 0; }
  27256. if (toFrame === void 0) { toFrame = 100; }
  27257. if (loopAnimation === void 0) { loopAnimation = false; }
  27258. if (speedRatio === void 0) { speedRatio = 1.0; }
  27259. this.target = target;
  27260. this.fromFrame = fromFrame;
  27261. this.toFrame = toFrame;
  27262. this.loopAnimation = loopAnimation;
  27263. this.speedRatio = speedRatio;
  27264. this.onAnimationEnd = onAnimationEnd;
  27265. this._animations = new Array();
  27266. this._paused = false;
  27267. this.animationStarted = false;
  27268. if (animations) {
  27269. this.appendAnimations(target, animations);
  27270. }
  27271. this._scene = scene;
  27272. scene._activeAnimatables.push(this);
  27273. }
  27274. // Methods
  27275. Animatable.prototype.getAnimations = function () {
  27276. return this._animations;
  27277. };
  27278. Animatable.prototype.appendAnimations = function (target, animations) {
  27279. for (var index = 0; index < animations.length; index++) {
  27280. var animation = animations[index];
  27281. animation._target = target;
  27282. this._animations.push(animation);
  27283. }
  27284. };
  27285. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27286. var animations = this._animations;
  27287. for (var index = 0; index < animations.length; index++) {
  27288. if (animations[index].targetProperty === property) {
  27289. return animations[index];
  27290. }
  27291. }
  27292. return null;
  27293. };
  27294. Animatable.prototype.reset = function () {
  27295. var animations = this._animations;
  27296. for (var index = 0; index < animations.length; index++) {
  27297. animations[index].reset();
  27298. }
  27299. this._localDelayOffset = null;
  27300. this._pausedDelay = null;
  27301. };
  27302. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27303. var animations = this._animations;
  27304. for (var index = 0; index < animations.length; index++) {
  27305. animations[index].enableBlending = true;
  27306. animations[index].blendingSpeed = blendingSpeed;
  27307. }
  27308. };
  27309. Animatable.prototype.disableBlending = function () {
  27310. var animations = this._animations;
  27311. for (var index = 0; index < animations.length; index++) {
  27312. animations[index].enableBlending = false;
  27313. }
  27314. };
  27315. Animatable.prototype.goToFrame = function (frame) {
  27316. var animations = this._animations;
  27317. for (var index = 0; index < animations.length; index++) {
  27318. animations[index].goToFrame(frame);
  27319. }
  27320. };
  27321. Animatable.prototype.pause = function () {
  27322. if (this._paused) {
  27323. return;
  27324. }
  27325. this._paused = true;
  27326. };
  27327. Animatable.prototype.restart = function () {
  27328. this._paused = false;
  27329. };
  27330. Animatable.prototype.stop = function () {
  27331. var index = this._scene._activeAnimatables.indexOf(this);
  27332. if (index > -1) {
  27333. this._scene._activeAnimatables.splice(index, 1);
  27334. var animations = this._animations;
  27335. for (var index = 0; index < animations.length; index++) {
  27336. animations[index].reset();
  27337. }
  27338. if (this.onAnimationEnd) {
  27339. this.onAnimationEnd();
  27340. }
  27341. }
  27342. };
  27343. Animatable.prototype._animate = function (delay) {
  27344. if (this._paused) {
  27345. this.animationStarted = false;
  27346. if (!this._pausedDelay) {
  27347. this._pausedDelay = delay;
  27348. }
  27349. return true;
  27350. }
  27351. if (!this._localDelayOffset) {
  27352. this._localDelayOffset = delay;
  27353. }
  27354. else if (this._pausedDelay) {
  27355. this._localDelayOffset += delay - this._pausedDelay;
  27356. this._pausedDelay = null;
  27357. }
  27358. // Animating
  27359. var running = false;
  27360. var animations = this._animations;
  27361. var index;
  27362. for (index = 0; index < animations.length; index++) {
  27363. var animation = animations[index];
  27364. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27365. running = running || isRunning;
  27366. }
  27367. this.animationStarted = running;
  27368. if (!running) {
  27369. // Remove from active animatables
  27370. index = this._scene._activeAnimatables.indexOf(this);
  27371. this._scene._activeAnimatables.splice(index, 1);
  27372. }
  27373. if (!running && this.onAnimationEnd) {
  27374. this.onAnimationEnd();
  27375. this.onAnimationEnd = null;
  27376. }
  27377. return running;
  27378. };
  27379. return Animatable;
  27380. })();
  27381. BABYLON.Animatable = Animatable;
  27382. })(BABYLON || (BABYLON = {}));
  27383. var BABYLON;
  27384. (function (BABYLON) {
  27385. var EasingFunction = (function () {
  27386. function EasingFunction() {
  27387. // Properties
  27388. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27389. }
  27390. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27391. get: function () {
  27392. return EasingFunction._EASINGMODE_EASEIN;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27398. get: function () {
  27399. return EasingFunction._EASINGMODE_EASEOUT;
  27400. },
  27401. enumerable: true,
  27402. configurable: true
  27403. });
  27404. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27405. get: function () {
  27406. return EasingFunction._EASINGMODE_EASEINOUT;
  27407. },
  27408. enumerable: true,
  27409. configurable: true
  27410. });
  27411. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27412. var n = Math.min(Math.max(easingMode, 0), 2);
  27413. this._easingMode = n;
  27414. };
  27415. EasingFunction.prototype.getEasingMode = function () {
  27416. return this._easingMode;
  27417. };
  27418. EasingFunction.prototype.easeInCore = function (gradient) {
  27419. throw new Error('You must implement this method');
  27420. };
  27421. EasingFunction.prototype.ease = function (gradient) {
  27422. switch (this._easingMode) {
  27423. case EasingFunction.EASINGMODE_EASEIN:
  27424. return this.easeInCore(gradient);
  27425. case EasingFunction.EASINGMODE_EASEOUT:
  27426. return (1 - this.easeInCore(1 - gradient));
  27427. }
  27428. if (gradient >= 0.5) {
  27429. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27430. }
  27431. return (this.easeInCore(gradient * 2) * 0.5);
  27432. };
  27433. //Statics
  27434. EasingFunction._EASINGMODE_EASEIN = 0;
  27435. EasingFunction._EASINGMODE_EASEOUT = 1;
  27436. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27437. return EasingFunction;
  27438. })();
  27439. BABYLON.EasingFunction = EasingFunction;
  27440. var CircleEase = (function (_super) {
  27441. __extends(CircleEase, _super);
  27442. function CircleEase() {
  27443. _super.apply(this, arguments);
  27444. }
  27445. CircleEase.prototype.easeInCore = function (gradient) {
  27446. gradient = Math.max(0, Math.min(1, gradient));
  27447. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27448. };
  27449. return CircleEase;
  27450. })(EasingFunction);
  27451. BABYLON.CircleEase = CircleEase;
  27452. var BackEase = (function (_super) {
  27453. __extends(BackEase, _super);
  27454. function BackEase(amplitude) {
  27455. if (amplitude === void 0) { amplitude = 1; }
  27456. _super.call(this);
  27457. this.amplitude = amplitude;
  27458. }
  27459. BackEase.prototype.easeInCore = function (gradient) {
  27460. var num = Math.max(0, this.amplitude);
  27461. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27462. };
  27463. return BackEase;
  27464. })(EasingFunction);
  27465. BABYLON.BackEase = BackEase;
  27466. var BounceEase = (function (_super) {
  27467. __extends(BounceEase, _super);
  27468. function BounceEase(bounces, bounciness) {
  27469. if (bounces === void 0) { bounces = 3; }
  27470. if (bounciness === void 0) { bounciness = 2; }
  27471. _super.call(this);
  27472. this.bounces = bounces;
  27473. this.bounciness = bounciness;
  27474. }
  27475. BounceEase.prototype.easeInCore = function (gradient) {
  27476. var y = Math.max(0.0, this.bounces);
  27477. var bounciness = this.bounciness;
  27478. if (bounciness <= 1.0) {
  27479. bounciness = 1.001;
  27480. }
  27481. var num9 = Math.pow(bounciness, y);
  27482. var num5 = 1.0 - bounciness;
  27483. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27484. var num15 = gradient * num4;
  27485. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27486. var num3 = Math.floor(num65);
  27487. var num13 = num3 + 1.0;
  27488. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27489. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27490. var num7 = (num8 + num12) * 0.5;
  27491. var num6 = gradient - num7;
  27492. var num2 = num7 - num8;
  27493. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27494. };
  27495. return BounceEase;
  27496. })(EasingFunction);
  27497. BABYLON.BounceEase = BounceEase;
  27498. var CubicEase = (function (_super) {
  27499. __extends(CubicEase, _super);
  27500. function CubicEase() {
  27501. _super.apply(this, arguments);
  27502. }
  27503. CubicEase.prototype.easeInCore = function (gradient) {
  27504. return (gradient * gradient * gradient);
  27505. };
  27506. return CubicEase;
  27507. })(EasingFunction);
  27508. BABYLON.CubicEase = CubicEase;
  27509. var ElasticEase = (function (_super) {
  27510. __extends(ElasticEase, _super);
  27511. function ElasticEase(oscillations, springiness) {
  27512. if (oscillations === void 0) { oscillations = 3; }
  27513. if (springiness === void 0) { springiness = 3; }
  27514. _super.call(this);
  27515. this.oscillations = oscillations;
  27516. this.springiness = springiness;
  27517. }
  27518. ElasticEase.prototype.easeInCore = function (gradient) {
  27519. var num2;
  27520. var num3 = Math.max(0.0, this.oscillations);
  27521. var num = Math.max(0.0, this.springiness);
  27522. if (num == 0) {
  27523. num2 = gradient;
  27524. }
  27525. else {
  27526. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27527. }
  27528. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27529. };
  27530. return ElasticEase;
  27531. })(EasingFunction);
  27532. BABYLON.ElasticEase = ElasticEase;
  27533. var ExponentialEase = (function (_super) {
  27534. __extends(ExponentialEase, _super);
  27535. function ExponentialEase(exponent) {
  27536. if (exponent === void 0) { exponent = 2; }
  27537. _super.call(this);
  27538. this.exponent = exponent;
  27539. }
  27540. ExponentialEase.prototype.easeInCore = function (gradient) {
  27541. if (this.exponent <= 0) {
  27542. return gradient;
  27543. }
  27544. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27545. };
  27546. return ExponentialEase;
  27547. })(EasingFunction);
  27548. BABYLON.ExponentialEase = ExponentialEase;
  27549. var PowerEase = (function (_super) {
  27550. __extends(PowerEase, _super);
  27551. function PowerEase(power) {
  27552. if (power === void 0) { power = 2; }
  27553. _super.call(this);
  27554. this.power = power;
  27555. }
  27556. PowerEase.prototype.easeInCore = function (gradient) {
  27557. var y = Math.max(0.0, this.power);
  27558. return Math.pow(gradient, y);
  27559. };
  27560. return PowerEase;
  27561. })(EasingFunction);
  27562. BABYLON.PowerEase = PowerEase;
  27563. var QuadraticEase = (function (_super) {
  27564. __extends(QuadraticEase, _super);
  27565. function QuadraticEase() {
  27566. _super.apply(this, arguments);
  27567. }
  27568. QuadraticEase.prototype.easeInCore = function (gradient) {
  27569. return (gradient * gradient);
  27570. };
  27571. return QuadraticEase;
  27572. })(EasingFunction);
  27573. BABYLON.QuadraticEase = QuadraticEase;
  27574. var QuarticEase = (function (_super) {
  27575. __extends(QuarticEase, _super);
  27576. function QuarticEase() {
  27577. _super.apply(this, arguments);
  27578. }
  27579. QuarticEase.prototype.easeInCore = function (gradient) {
  27580. return (gradient * gradient * gradient * gradient);
  27581. };
  27582. return QuarticEase;
  27583. })(EasingFunction);
  27584. BABYLON.QuarticEase = QuarticEase;
  27585. var QuinticEase = (function (_super) {
  27586. __extends(QuinticEase, _super);
  27587. function QuinticEase() {
  27588. _super.apply(this, arguments);
  27589. }
  27590. QuinticEase.prototype.easeInCore = function (gradient) {
  27591. return (gradient * gradient * gradient * gradient * gradient);
  27592. };
  27593. return QuinticEase;
  27594. })(EasingFunction);
  27595. BABYLON.QuinticEase = QuinticEase;
  27596. var SineEase = (function (_super) {
  27597. __extends(SineEase, _super);
  27598. function SineEase() {
  27599. _super.apply(this, arguments);
  27600. }
  27601. SineEase.prototype.easeInCore = function (gradient) {
  27602. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27603. };
  27604. return SineEase;
  27605. })(EasingFunction);
  27606. BABYLON.SineEase = SineEase;
  27607. var BezierCurveEase = (function (_super) {
  27608. __extends(BezierCurveEase, _super);
  27609. function BezierCurveEase(x1, y1, x2, y2) {
  27610. if (x1 === void 0) { x1 = 0; }
  27611. if (y1 === void 0) { y1 = 0; }
  27612. if (x2 === void 0) { x2 = 1; }
  27613. if (y2 === void 0) { y2 = 1; }
  27614. _super.call(this);
  27615. this.x1 = x1;
  27616. this.y1 = y1;
  27617. this.x2 = x2;
  27618. this.y2 = y2;
  27619. }
  27620. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27621. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27622. };
  27623. return BezierCurveEase;
  27624. })(EasingFunction);
  27625. BABYLON.BezierCurveEase = BezierCurveEase;
  27626. })(BABYLON || (BABYLON = {}));
  27627. var BABYLON;
  27628. (function (BABYLON) {
  27629. var Bone = (function (_super) {
  27630. __extends(Bone, _super);
  27631. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27632. _super.call(this, name, skeleton.getScene());
  27633. this.name = name;
  27634. this.children = new Array();
  27635. this.animations = new Array();
  27636. this._worldTransform = new BABYLON.Matrix();
  27637. this._absoluteTransform = new BABYLON.Matrix();
  27638. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27639. this._skeleton = skeleton;
  27640. this._matrix = matrix;
  27641. this._baseMatrix = matrix;
  27642. this._restPose = restPose ? restPose : matrix.clone();
  27643. skeleton.bones.push(this);
  27644. if (parentBone) {
  27645. this._parent = parentBone;
  27646. parentBone.children.push(this);
  27647. }
  27648. else {
  27649. this._parent = null;
  27650. }
  27651. this._updateDifferenceMatrix();
  27652. }
  27653. // Members
  27654. Bone.prototype.getParent = function () {
  27655. return this._parent;
  27656. };
  27657. Bone.prototype.getLocalMatrix = function () {
  27658. return this._matrix;
  27659. };
  27660. Bone.prototype.getBaseMatrix = function () {
  27661. return this._baseMatrix;
  27662. };
  27663. Bone.prototype.getRestPose = function () {
  27664. return this._restPose;
  27665. };
  27666. Bone.prototype.returnToRest = function () {
  27667. this.updateMatrix(this._restPose.clone());
  27668. };
  27669. Bone.prototype.getWorldMatrix = function () {
  27670. return this._worldTransform;
  27671. };
  27672. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27673. return this._invertedAbsoluteTransform;
  27674. };
  27675. Bone.prototype.getAbsoluteTransform = function () {
  27676. return this._absoluteTransform;
  27677. };
  27678. // Methods
  27679. Bone.prototype.updateMatrix = function (matrix) {
  27680. this._baseMatrix = matrix.clone();
  27681. this._matrix = matrix.clone();
  27682. this._skeleton._markAsDirty();
  27683. this._updateDifferenceMatrix();
  27684. };
  27685. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27686. if (!rootMatrix) {
  27687. rootMatrix = this._baseMatrix;
  27688. }
  27689. if (this._parent) {
  27690. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27691. }
  27692. else {
  27693. this._absoluteTransform.copyFrom(rootMatrix);
  27694. }
  27695. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27696. for (var index = 0; index < this.children.length; index++) {
  27697. this.children[index]._updateDifferenceMatrix();
  27698. }
  27699. };
  27700. Bone.prototype.markAsDirty = function () {
  27701. this._currentRenderId++;
  27702. this._skeleton._markAsDirty();
  27703. };
  27704. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27705. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27706. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27707. // all animation may be coming from a library skeleton, so may need to create animation
  27708. if (this.animations.length === 0) {
  27709. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27710. this.animations[0].setKeys([]);
  27711. }
  27712. // get animation info / verify there is such a range from the source bone
  27713. var sourceRange = source.animations[0].getRange(rangeName);
  27714. if (!sourceRange) {
  27715. return false;
  27716. }
  27717. var from = sourceRange.from;
  27718. var to = sourceRange.to;
  27719. var sourceKeys = source.animations[0].getKeys();
  27720. // rescaling prep
  27721. var sourceBoneLength = source.length;
  27722. var sourceParent = source.getParent();
  27723. var parent = this.getParent();
  27724. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27725. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27726. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27727. var destKeys = this.animations[0].getKeys();
  27728. // loop vars declaration
  27729. var orig;
  27730. var origTranslation;
  27731. var mat;
  27732. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27733. orig = sourceKeys[key];
  27734. if (orig.frame >= from && orig.frame <= to) {
  27735. if (rescaleAsRequired) {
  27736. mat = orig.value.clone();
  27737. // scale based on parent ratio, when bone has parent
  27738. if (parentScalingReqd) {
  27739. origTranslation = mat.getTranslation();
  27740. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27741. }
  27742. else if (dimensionsScalingReqd) {
  27743. origTranslation = mat.getTranslation();
  27744. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27745. }
  27746. else {
  27747. mat = orig.value;
  27748. }
  27749. }
  27750. else {
  27751. mat = orig.value;
  27752. }
  27753. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27754. }
  27755. }
  27756. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27757. return true;
  27758. };
  27759. return Bone;
  27760. })(BABYLON.Node);
  27761. BABYLON.Bone = Bone;
  27762. })(BABYLON || (BABYLON = {}));
  27763. var BABYLON;
  27764. (function (BABYLON) {
  27765. var Skeleton = (function () {
  27766. function Skeleton(name, id, scene) {
  27767. this.name = name;
  27768. this.id = id;
  27769. this.bones = new Array();
  27770. this.needInitialSkinMatrix = false;
  27771. this._isDirty = true;
  27772. this._meshesWithPoseMatrix = new Array();
  27773. this._identity = BABYLON.Matrix.Identity();
  27774. this._ranges = {};
  27775. this.bones = [];
  27776. this._scene = scene;
  27777. scene.skeletons.push(this);
  27778. //make sure it will recalculate the matrix next time prepare is called.
  27779. this._isDirty = true;
  27780. }
  27781. // Members
  27782. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27783. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27784. return mesh._bonesTransformMatrices;
  27785. }
  27786. return this._transformMatrices;
  27787. };
  27788. Skeleton.prototype.getScene = function () {
  27789. return this._scene;
  27790. };
  27791. // Methods
  27792. /**
  27793. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27794. */
  27795. Skeleton.prototype.toString = function (fullDetails) {
  27796. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27797. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27798. if (fullDetails) {
  27799. ret += ", Ranges: {";
  27800. var first = true;
  27801. for (var name_1 in this._ranges) {
  27802. if (first) {
  27803. ret += ", ";
  27804. first = false;
  27805. }
  27806. ret += name_1;
  27807. }
  27808. ret += "}";
  27809. }
  27810. return ret;
  27811. };
  27812. /**
  27813. * Get bone's index searching by name
  27814. * @param {string} name is bone's name to search for
  27815. * @return {number} Indice of the bone. Returns -1 if not found
  27816. */
  27817. Skeleton.prototype.getBoneIndexByName = function (name) {
  27818. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27819. if (this.bones[boneIndex].name === name) {
  27820. return boneIndex;
  27821. }
  27822. }
  27823. return -1;
  27824. };
  27825. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27826. // check name not already in use
  27827. if (!this._ranges[name]) {
  27828. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27829. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27830. if (this.bones[i].animations[0]) {
  27831. this.bones[i].animations[0].createRange(name, from, to);
  27832. }
  27833. }
  27834. }
  27835. };
  27836. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27837. if (deleteFrames === void 0) { deleteFrames = true; }
  27838. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27839. if (this.bones[i].animations[0]) {
  27840. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27841. }
  27842. }
  27843. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27844. };
  27845. Skeleton.prototype.getAnimationRange = function (name) {
  27846. return this._ranges[name];
  27847. };
  27848. /**
  27849. * Returns as an Array, all AnimationRanges defined on this skeleton
  27850. */
  27851. Skeleton.prototype.getAnimationRanges = function () {
  27852. var animationRanges = [];
  27853. var name;
  27854. var i = 0;
  27855. for (name in this._ranges) {
  27856. animationRanges[i] = this._ranges[name];
  27857. i++;
  27858. }
  27859. return animationRanges;
  27860. };
  27861. /**
  27862. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27863. */
  27864. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27865. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27866. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27867. return false;
  27868. }
  27869. var ret = true;
  27870. var frameOffset = this._getHighestAnimationFrame() + 1;
  27871. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27872. var boneDict = {};
  27873. var sourceBones = source.bones;
  27874. var nBones;
  27875. var i;
  27876. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27877. boneDict[sourceBones[i].name] = sourceBones[i];
  27878. }
  27879. if (this.bones.length !== sourceBones.length) {
  27880. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27881. ret = false;
  27882. }
  27883. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  27884. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27885. var boneName = this.bones[i].name;
  27886. var sourceBone = boneDict[boneName];
  27887. if (sourceBone) {
  27888. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  27889. }
  27890. else {
  27891. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27892. ret = false;
  27893. }
  27894. }
  27895. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27896. var range = source.getAnimationRange(name);
  27897. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27898. return ret;
  27899. };
  27900. Skeleton.prototype.returnToRest = function () {
  27901. for (var index = 0; index < this.bones.length; index++) {
  27902. this.bones[index].returnToRest();
  27903. }
  27904. };
  27905. Skeleton.prototype._getHighestAnimationFrame = function () {
  27906. var ret = 0;
  27907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27908. if (this.bones[i].animations[0]) {
  27909. var highest = this.bones[i].animations[0].getHighestFrame();
  27910. if (ret < highest) {
  27911. ret = highest;
  27912. }
  27913. }
  27914. }
  27915. return ret;
  27916. };
  27917. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27918. var range = this.getAnimationRange(name);
  27919. if (!range) {
  27920. return null;
  27921. }
  27922. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27923. };
  27924. Skeleton.prototype._markAsDirty = function () {
  27925. this._isDirty = true;
  27926. };
  27927. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27928. this._meshesWithPoseMatrix.push(mesh);
  27929. };
  27930. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27931. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27932. if (index > -1) {
  27933. this._meshesWithPoseMatrix.splice(index, 1);
  27934. }
  27935. };
  27936. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27937. for (var index = 0; index < this.bones.length; index++) {
  27938. var bone = this.bones[index];
  27939. var parentBone = bone.getParent();
  27940. if (parentBone) {
  27941. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27942. }
  27943. else {
  27944. if (initialSkinMatrix) {
  27945. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  27946. }
  27947. else {
  27948. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  27949. }
  27950. }
  27951. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  27952. }
  27953. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  27954. };
  27955. Skeleton.prototype.prepare = function () {
  27956. if (!this._isDirty) {
  27957. return;
  27958. }
  27959. if (this.needInitialSkinMatrix) {
  27960. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  27961. var mesh = this._meshesWithPoseMatrix[index];
  27962. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  27963. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27964. }
  27965. var poseMatrix = mesh.getPoseMatrix();
  27966. // Prepare bones
  27967. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27968. var bone = this.bones[boneIndex];
  27969. if (!bone.getParent()) {
  27970. var matrix = bone.getBaseMatrix();
  27971. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27972. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27973. }
  27974. }
  27975. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27976. }
  27977. }
  27978. else {
  27979. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27980. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27981. }
  27982. this._computeTransformMatrices(this._transformMatrices, null);
  27983. }
  27984. this._isDirty = false;
  27985. this._scene._activeBones.addCount(this.bones.length, false);
  27986. };
  27987. Skeleton.prototype.getAnimatables = function () {
  27988. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27989. this._animatables = [];
  27990. for (var index = 0; index < this.bones.length; index++) {
  27991. this._animatables.push(this.bones[index]);
  27992. }
  27993. }
  27994. return this._animatables;
  27995. };
  27996. Skeleton.prototype.clone = function (name, id) {
  27997. var result = new Skeleton(name, id || name, this._scene);
  27998. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27999. for (var index = 0; index < this.bones.length; index++) {
  28000. var source = this.bones[index];
  28001. var parentBone = null;
  28002. if (source.getParent()) {
  28003. var parentIndex = this.bones.indexOf(source.getParent());
  28004. parentBone = result.bones[parentIndex];
  28005. }
  28006. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28007. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28008. }
  28009. if (this._ranges) {
  28010. result._ranges = {};
  28011. for (var rangeName in this._ranges) {
  28012. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28013. }
  28014. }
  28015. this._isDirty = true;
  28016. return result;
  28017. };
  28018. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28019. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28020. this.bones.forEach(function (bone) {
  28021. bone.animations.forEach(function (animation) {
  28022. animation.enableBlending = true;
  28023. animation.blendingSpeed = blendingSpeed;
  28024. });
  28025. });
  28026. };
  28027. Skeleton.prototype.dispose = function () {
  28028. this._meshesWithPoseMatrix = [];
  28029. // Animations
  28030. this.getScene().stopAnimation(this);
  28031. // Remove from scene
  28032. this.getScene().removeSkeleton(this);
  28033. };
  28034. Skeleton.prototype.serialize = function () {
  28035. var serializationObject = {};
  28036. serializationObject.name = this.name;
  28037. serializationObject.id = this.id;
  28038. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28039. serializationObject.bones = [];
  28040. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28041. for (var index = 0; index < this.bones.length; index++) {
  28042. var bone = this.bones[index];
  28043. var serializedBone = {
  28044. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28045. name: bone.name,
  28046. matrix: bone.getLocalMatrix().toArray(),
  28047. rest: bone.getRestPose().toArray()
  28048. };
  28049. serializationObject.bones.push(serializedBone);
  28050. if (bone.length) {
  28051. serializedBone.length = bone.length;
  28052. }
  28053. if (bone.animations && bone.animations.length > 0) {
  28054. serializedBone.animation = bone.animations[0].serialize();
  28055. }
  28056. serializationObject.ranges = [];
  28057. for (var name in this._ranges) {
  28058. var range = {};
  28059. range.name = name;
  28060. range.from = this._ranges[name].from;
  28061. range.to = this._ranges[name].to;
  28062. serializationObject.ranges.push(range);
  28063. }
  28064. }
  28065. return serializationObject;
  28066. };
  28067. Skeleton.Parse = function (parsedSkeleton, scene) {
  28068. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28069. if (parsedSkeleton.dimensionsAtRest) {
  28070. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28071. }
  28072. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28073. var index;
  28074. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28075. var parsedBone = parsedSkeleton.bones[index];
  28076. var parentBone = null;
  28077. if (parsedBone.parentBoneIndex > -1) {
  28078. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28079. }
  28080. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28081. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28082. if (parsedBone.length) {
  28083. bone.length = parsedBone.length;
  28084. }
  28085. if (parsedBone.animation) {
  28086. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28087. }
  28088. }
  28089. // placed after bones, so createAnimationRange can cascade down
  28090. if (parsedSkeleton.ranges) {
  28091. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28092. var data = parsedSkeleton.ranges[index];
  28093. skeleton.createAnimationRange(data.name, data.from, data.to);
  28094. }
  28095. }
  28096. return skeleton;
  28097. };
  28098. return Skeleton;
  28099. })();
  28100. BABYLON.Skeleton = Skeleton;
  28101. })(BABYLON || (BABYLON = {}));
  28102. var BABYLON;
  28103. (function (BABYLON) {
  28104. var PostProcess = (function () {
  28105. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28107. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28108. this.name = name;
  28109. this.width = -1;
  28110. this.height = -1;
  28111. /*
  28112. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28113. Can only be used on a single postprocess or on the last one of a chain.
  28114. */
  28115. this.enablePixelPerfectMode = false;
  28116. this._reusable = false;
  28117. this._textures = new BABYLON.SmartArray(2);
  28118. this._currentRenderTextureInd = 0;
  28119. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28120. // Events
  28121. /**
  28122. * An event triggered when the postprocess is activated.
  28123. * @type {BABYLON.Observable}
  28124. */
  28125. this.onActivateObservable = new BABYLON.Observable();
  28126. /**
  28127. * An event triggered when the postprocess changes its size.
  28128. * @type {BABYLON.Observable}
  28129. */
  28130. this.onSizeChangedObservable = new BABYLON.Observable();
  28131. /**
  28132. * An event triggered when the postprocess applies its effect.
  28133. * @type {BABYLON.Observable}
  28134. */
  28135. this.onApplyObservable = new BABYLON.Observable();
  28136. /**
  28137. * An event triggered before rendering the postprocess
  28138. * @type {BABYLON.Observable}
  28139. */
  28140. this.onBeforeRenderObservable = new BABYLON.Observable();
  28141. /**
  28142. * An event triggered after rendering the postprocess
  28143. * @type {BABYLON.Observable}
  28144. */
  28145. this.onAfterRenderObservable = new BABYLON.Observable();
  28146. if (camera != null) {
  28147. this._camera = camera;
  28148. this._scene = camera.getScene();
  28149. camera.attachPostProcess(this);
  28150. this._engine = this._scene.getEngine();
  28151. }
  28152. else {
  28153. this._engine = engine;
  28154. }
  28155. this._options = options;
  28156. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28157. this._reusable = reusable || false;
  28158. this._textureType = textureType;
  28159. this._samplers = samplers || [];
  28160. this._samplers.push("textureSampler");
  28161. this._fragmentUrl = fragmentUrl;
  28162. this._parameters = parameters || [];
  28163. this._parameters.push("scale");
  28164. this.updateEffect(defines);
  28165. }
  28166. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28167. set: function (callback) {
  28168. if (this._onActivateObserver) {
  28169. this.onActivateObservable.remove(this._onActivateObserver);
  28170. }
  28171. this._onActivateObserver = this.onActivateObservable.add(callback);
  28172. },
  28173. enumerable: true,
  28174. configurable: true
  28175. });
  28176. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28177. set: function (callback) {
  28178. if (this._onSizeChangedObserver) {
  28179. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28180. }
  28181. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28182. },
  28183. enumerable: true,
  28184. configurable: true
  28185. });
  28186. Object.defineProperty(PostProcess.prototype, "onApply", {
  28187. set: function (callback) {
  28188. if (this._onApplyObserver) {
  28189. this.onApplyObservable.remove(this._onApplyObserver);
  28190. }
  28191. this._onApplyObserver = this.onApplyObservable.add(callback);
  28192. },
  28193. enumerable: true,
  28194. configurable: true
  28195. });
  28196. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28197. set: function (callback) {
  28198. if (this._onBeforeRenderObserver) {
  28199. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28200. }
  28201. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28202. },
  28203. enumerable: true,
  28204. configurable: true
  28205. });
  28206. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28207. set: function (callback) {
  28208. if (this._onAfterRenderObserver) {
  28209. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28210. }
  28211. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28212. },
  28213. enumerable: true,
  28214. configurable: true
  28215. });
  28216. PostProcess.prototype.updateEffect = function (defines) {
  28217. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28218. };
  28219. PostProcess.prototype.isReusable = function () {
  28220. return this._reusable;
  28221. };
  28222. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28223. PostProcess.prototype.markTextureDirty = function () {
  28224. this.width = -1;
  28225. };
  28226. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28227. camera = camera || this._camera;
  28228. var scene = camera.getScene();
  28229. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28230. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28231. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28232. var desiredWidth = this._options.width || requiredWidth;
  28233. var desiredHeight = this._options.height || requiredHeight;
  28234. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28235. if (!this._options.width) {
  28236. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28237. }
  28238. if (!this._options.height) {
  28239. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28240. }
  28241. }
  28242. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28243. if (this._textures.length > 0) {
  28244. for (var i = 0; i < this._textures.length; i++) {
  28245. this._engine._releaseTexture(this._textures.data[i]);
  28246. }
  28247. this._textures.reset();
  28248. }
  28249. this.width = desiredWidth;
  28250. this.height = desiredHeight;
  28251. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28252. if (this._reusable) {
  28253. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28254. }
  28255. this.onSizeChangedObservable.notifyObservers(this);
  28256. }
  28257. if (this.enablePixelPerfectMode) {
  28258. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28259. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28260. }
  28261. else {
  28262. this._scaleRatio.copyFromFloats(1, 1);
  28263. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28264. }
  28265. this.onActivateObservable.notifyObservers(camera);
  28266. // Clear
  28267. if (this.clearColor) {
  28268. this._engine.clear(this.clearColor, true, true);
  28269. }
  28270. else {
  28271. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28272. }
  28273. if (this._reusable) {
  28274. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28275. }
  28276. };
  28277. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28278. get: function () {
  28279. return this._effect.isSupported;
  28280. },
  28281. enumerable: true,
  28282. configurable: true
  28283. });
  28284. PostProcess.prototype.apply = function () {
  28285. // Check
  28286. if (!this._effect.isReady())
  28287. return null;
  28288. // States
  28289. this._engine.enableEffect(this._effect);
  28290. this._engine.setState(false);
  28291. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28292. this._engine.setDepthBuffer(false);
  28293. this._engine.setDepthWrite(false);
  28294. // Texture
  28295. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28296. // Parameters
  28297. this._effect.setVector2("scale", this._scaleRatio);
  28298. this.onApplyObservable.notifyObservers(this._effect);
  28299. return this._effect;
  28300. };
  28301. PostProcess.prototype.dispose = function (camera) {
  28302. camera = camera || this._camera;
  28303. if (this._textures.length > 0) {
  28304. for (var i = 0; i < this._textures.length; i++) {
  28305. this._engine._releaseTexture(this._textures.data[i]);
  28306. }
  28307. this._textures.reset();
  28308. }
  28309. if (!camera) {
  28310. return;
  28311. }
  28312. camera.detachPostProcess(this);
  28313. var index = camera._postProcesses.indexOf(this);
  28314. if (index === 0 && camera._postProcesses.length > 0) {
  28315. this._camera._postProcesses[0].markTextureDirty();
  28316. }
  28317. this.onActivateObservable.clear();
  28318. this.onAfterRenderObservable.clear();
  28319. this.onApplyObservable.clear();
  28320. this.onBeforeRenderObservable.clear();
  28321. this.onSizeChangedObservable.clear();
  28322. };
  28323. return PostProcess;
  28324. })();
  28325. BABYLON.PostProcess = PostProcess;
  28326. })(BABYLON || (BABYLON = {}));
  28327. var BABYLON;
  28328. (function (BABYLON) {
  28329. var PostProcessManager = (function () {
  28330. function PostProcessManager(scene) {
  28331. this._vertexBuffers = {};
  28332. this._scene = scene;
  28333. }
  28334. PostProcessManager.prototype._prepareBuffers = function () {
  28335. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28336. return;
  28337. }
  28338. // VBO
  28339. var vertices = [];
  28340. vertices.push(1, 1);
  28341. vertices.push(-1, 1);
  28342. vertices.push(-1, -1);
  28343. vertices.push(1, -1);
  28344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28345. // Indices
  28346. var indices = [];
  28347. indices.push(0);
  28348. indices.push(1);
  28349. indices.push(2);
  28350. indices.push(0);
  28351. indices.push(2);
  28352. indices.push(3);
  28353. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28354. };
  28355. // Methods
  28356. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28357. var postProcesses = this._scene.activeCamera._postProcesses;
  28358. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28359. return false;
  28360. }
  28361. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28362. return true;
  28363. };
  28364. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28365. var engine = this._scene.getEngine();
  28366. for (var index = 0; index < postProcesses.length; index++) {
  28367. if (index < postProcesses.length - 1) {
  28368. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28369. }
  28370. else {
  28371. if (targetTexture) {
  28372. engine.bindFramebuffer(targetTexture);
  28373. }
  28374. else {
  28375. engine.restoreDefaultFramebuffer();
  28376. }
  28377. }
  28378. var pp = postProcesses[index];
  28379. var effect = pp.apply();
  28380. if (effect) {
  28381. pp.onBeforeRenderObservable.notifyObservers(effect);
  28382. // VBOs
  28383. this._prepareBuffers();
  28384. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28385. // Draw order
  28386. engine.draw(true, 0, 6);
  28387. pp.onAfterRenderObservable.notifyObservers(effect);
  28388. }
  28389. }
  28390. // Restore depth buffer
  28391. engine.setDepthBuffer(true);
  28392. engine.setDepthWrite(true);
  28393. };
  28394. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28395. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28396. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28397. return;
  28398. }
  28399. var engine = this._scene.getEngine();
  28400. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28401. if (index < len - 1) {
  28402. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28403. }
  28404. else {
  28405. if (targetTexture) {
  28406. engine.bindFramebuffer(targetTexture, faceIndex);
  28407. }
  28408. else {
  28409. engine.restoreDefaultFramebuffer();
  28410. }
  28411. }
  28412. if (doNotPresent) {
  28413. break;
  28414. }
  28415. var pp = postProcesses[index];
  28416. var effect = pp.apply();
  28417. if (effect) {
  28418. pp.onBeforeRenderObservable.notifyObservers(effect);
  28419. // VBOs
  28420. this._prepareBuffers();
  28421. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28422. // Draw order
  28423. engine.draw(true, 0, 6);
  28424. pp.onAfterRenderObservable.notifyObservers(effect);
  28425. }
  28426. }
  28427. // Restore depth buffer
  28428. engine.setDepthBuffer(true);
  28429. engine.setDepthWrite(true);
  28430. };
  28431. PostProcessManager.prototype.dispose = function () {
  28432. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28433. if (buffer) {
  28434. buffer.dispose();
  28435. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28436. }
  28437. if (this._indexBuffer) {
  28438. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28439. this._indexBuffer = null;
  28440. }
  28441. };
  28442. return PostProcessManager;
  28443. })();
  28444. BABYLON.PostProcessManager = PostProcessManager;
  28445. })(BABYLON || (BABYLON = {}));
  28446. var BABYLON;
  28447. (function (BABYLON) {
  28448. var PassPostProcess = (function (_super) {
  28449. __extends(PassPostProcess, _super);
  28450. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28451. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28452. }
  28453. return PassPostProcess;
  28454. })(BABYLON.PostProcess);
  28455. BABYLON.PassPostProcess = PassPostProcess;
  28456. })(BABYLON || (BABYLON = {}));
  28457. var BABYLON;
  28458. (function (BABYLON) {
  28459. /**
  28460. * This is a holder class for the physics joint created by the physics plugin.
  28461. * It holds a set of functions to control the underlying joint.
  28462. */
  28463. var PhysicsJoint = (function () {
  28464. function PhysicsJoint(type, jointData) {
  28465. this.type = type;
  28466. this.jointData = jointData;
  28467. jointData.nativeParams = jointData.nativeParams || {};
  28468. }
  28469. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28470. get: function () {
  28471. return this._physicsJoint;
  28472. },
  28473. set: function (newJoint) {
  28474. if (this._physicsJoint) {
  28475. }
  28476. this._physicsJoint = newJoint;
  28477. },
  28478. enumerable: true,
  28479. configurable: true
  28480. });
  28481. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28482. set: function (physicsPlugin) {
  28483. this._physicsPlugin = physicsPlugin;
  28484. },
  28485. enumerable: true,
  28486. configurable: true
  28487. });
  28488. /**
  28489. * Execute a function that is physics-plugin specific.
  28490. * @param {Function} func the function that will be executed.
  28491. * It accepts two parameters: the physics world and the physics joint.
  28492. */
  28493. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28494. func(this._physicsPlugin.world, this._physicsJoint);
  28495. };
  28496. //TODO check if the native joints are the same
  28497. //Joint Types
  28498. PhysicsJoint.DistanceJoint = 0;
  28499. PhysicsJoint.HingeJoint = 1;
  28500. PhysicsJoint.BallAndSocketJoint = 2;
  28501. PhysicsJoint.WheelJoint = 3;
  28502. PhysicsJoint.SliderJoint = 4;
  28503. //OIMO
  28504. PhysicsJoint.PrismaticJoint = 5;
  28505. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28506. PhysicsJoint.UniversalJoint = 6;
  28507. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28508. //Cannon
  28509. //Similar to a Ball-Joint. Different in params
  28510. PhysicsJoint.PointToPointJoint = 8;
  28511. //Cannon only at the moment
  28512. PhysicsJoint.SpringJoint = 9;
  28513. PhysicsJoint.LockJoint = 10;
  28514. return PhysicsJoint;
  28515. })();
  28516. BABYLON.PhysicsJoint = PhysicsJoint;
  28517. /**
  28518. * A class representing a physics distance joint.
  28519. */
  28520. var DistanceJoint = (function (_super) {
  28521. __extends(DistanceJoint, _super);
  28522. function DistanceJoint(jointData) {
  28523. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28524. }
  28525. /**
  28526. * Update the predefined distance.
  28527. */
  28528. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28529. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28530. };
  28531. return DistanceJoint;
  28532. })(PhysicsJoint);
  28533. BABYLON.DistanceJoint = DistanceJoint;
  28534. var MotorEnabledJoint = (function (_super) {
  28535. __extends(MotorEnabledJoint, _super);
  28536. function MotorEnabledJoint(type, jointData) {
  28537. _super.call(this, type, jointData);
  28538. }
  28539. /**
  28540. * Set the motor values.
  28541. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28542. * @param {number} force the force to apply
  28543. * @param {number} maxForce max force for this motor.
  28544. */
  28545. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28546. this._physicsPlugin.setMotor(this, force, maxForce);
  28547. };
  28548. /**
  28549. * Set the motor's limits.
  28550. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28551. */
  28552. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28553. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28554. };
  28555. return MotorEnabledJoint;
  28556. })(PhysicsJoint);
  28557. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28558. /**
  28559. * This class represents a single hinge physics joint
  28560. */
  28561. var HingeJoint = (function (_super) {
  28562. __extends(HingeJoint, _super);
  28563. function HingeJoint(jointData) {
  28564. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28565. }
  28566. /**
  28567. * Set the motor values.
  28568. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28569. * @param {number} force the force to apply
  28570. * @param {number} maxForce max force for this motor.
  28571. */
  28572. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28573. this._physicsPlugin.setMotor(this, force, maxForce);
  28574. };
  28575. /**
  28576. * Set the motor's limits.
  28577. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28578. */
  28579. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28580. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28581. };
  28582. return HingeJoint;
  28583. })(MotorEnabledJoint);
  28584. BABYLON.HingeJoint = HingeJoint;
  28585. /**
  28586. * This class represents a dual hinge physics joint (same as wheel joint)
  28587. */
  28588. var Hinge2Joint = (function (_super) {
  28589. __extends(Hinge2Joint, _super);
  28590. function Hinge2Joint(jointData) {
  28591. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28592. }
  28593. /**
  28594. * Set the motor values.
  28595. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28596. * @param {number} force the force to apply
  28597. * @param {number} maxForce max force for this motor.
  28598. * @param {motorIndex} the motor's index, 0 or 1.
  28599. */
  28600. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28601. if (motorIndex === void 0) { motorIndex = 0; }
  28602. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28603. };
  28604. /**
  28605. * Set the motor limits.
  28606. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28607. * @param {number} upperLimit the upper limit
  28608. * @param {number} lowerLimit lower limit
  28609. * @param {motorIndex} the motor's index, 0 or 1.
  28610. */
  28611. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28612. if (motorIndex === void 0) { motorIndex = 0; }
  28613. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28614. };
  28615. return Hinge2Joint;
  28616. })(MotorEnabledJoint);
  28617. BABYLON.Hinge2Joint = Hinge2Joint;
  28618. })(BABYLON || (BABYLON = {}));
  28619. var BABYLON;
  28620. (function (BABYLON) {
  28621. var PhysicsImpostor = (function () {
  28622. function PhysicsImpostor(object, type, _options, _scene) {
  28623. var _this = this;
  28624. if (_options === void 0) { _options = { mass: 0 }; }
  28625. this.object = object;
  28626. this.type = type;
  28627. this._options = _options;
  28628. this._scene = _scene;
  28629. this._bodyUpdateRequired = false;
  28630. this._onBeforePhysicsStepCallbacks = new Array();
  28631. this._onAfterPhysicsStepCallbacks = new Array();
  28632. this._onPhysicsCollideCallbacks = [];
  28633. this._deltaPosition = BABYLON.Vector3.Zero();
  28634. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28635. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28636. /**
  28637. * this function is executed by the physics engine.
  28638. */
  28639. this.beforeStep = function () {
  28640. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28641. //conjugate deltaRotation
  28642. if (_this._deltaRotationConjugated) {
  28643. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28644. }
  28645. else {
  28646. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28647. }
  28648. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28649. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28650. func(_this);
  28651. });
  28652. };
  28653. /**
  28654. * this function is executed by the physics engine.
  28655. */
  28656. this.afterStep = function () {
  28657. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28658. func(_this);
  28659. });
  28660. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28661. _this.object.position.addInPlace(_this._deltaPosition);
  28662. if (_this._deltaRotation) {
  28663. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28664. }
  28665. };
  28666. //event and body object due to cannon's event-based architecture.
  28667. this.onCollide = function (e) {
  28668. if (!_this._onPhysicsCollideCallbacks.length)
  28669. return;
  28670. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28671. if (otherImpostor) {
  28672. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28673. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28674. }).forEach(function (obj) {
  28675. obj.callback(_this, otherImpostor);
  28676. });
  28677. }
  28678. };
  28679. //sanity check!
  28680. if (!this.object) {
  28681. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28682. return;
  28683. }
  28684. //legacy support for old syntax.
  28685. if (!this._scene && object.getScene) {
  28686. this._scene = object.getScene();
  28687. }
  28688. this._physicsEngine = this._scene.getPhysicsEngine();
  28689. if (!this._physicsEngine) {
  28690. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28691. }
  28692. else {
  28693. //set the object's quaternion, if not set
  28694. if (!this.object.rotationQuaternion) {
  28695. if (this.object.rotation) {
  28696. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28697. }
  28698. else {
  28699. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28700. }
  28701. }
  28702. //default options params
  28703. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28704. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28705. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28706. this._joints = [];
  28707. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28708. if (!this.object.parent) {
  28709. this._init();
  28710. }
  28711. }
  28712. }
  28713. /**
  28714. * This function will completly initialize this impostor.
  28715. * It will create a new body - but only if this mesh has no parent.
  28716. * If it has, this impostor will not be used other than to define the impostor
  28717. * of the child mesh.
  28718. */
  28719. PhysicsImpostor.prototype._init = function () {
  28720. this._physicsEngine.removeImpostor(this);
  28721. this.physicsBody = null;
  28722. this._parent = this._parent || this._getPhysicsParent();
  28723. if (!this.parent) {
  28724. this._physicsEngine.addImpostor(this);
  28725. }
  28726. };
  28727. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28728. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28729. var parentMesh = this.object.parent;
  28730. return parentMesh.physicsImpostor;
  28731. }
  28732. return;
  28733. };
  28734. /**
  28735. * Should a new body be generated.
  28736. */
  28737. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28738. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28739. };
  28740. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28741. this.forceUpdate();
  28742. };
  28743. /**
  28744. * Force a regeneration of this or the parent's impostor's body.
  28745. * Use under cautious - This will remove all joints already implemented.
  28746. */
  28747. PhysicsImpostor.prototype.forceUpdate = function () {
  28748. this._init();
  28749. if (this.parent) {
  28750. this.parent.forceUpdate();
  28751. }
  28752. };
  28753. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28754. /*public get mesh(): AbstractMesh {
  28755. return this._mesh;
  28756. }*/
  28757. /**
  28758. * Gets the body that holds this impostor. Either its own, or its parent.
  28759. */
  28760. get: function () {
  28761. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28762. },
  28763. /**
  28764. * Set the physics body. Used mainly by the physics engine/plugin
  28765. */
  28766. set: function (physicsBody) {
  28767. if (this._physicsBody) {
  28768. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28769. }
  28770. this._physicsBody = physicsBody;
  28771. this.resetUpdateFlags();
  28772. },
  28773. enumerable: true,
  28774. configurable: true
  28775. });
  28776. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28777. get: function () {
  28778. return this._parent;
  28779. },
  28780. enumerable: true,
  28781. configurable: true
  28782. });
  28783. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28784. this._bodyUpdateRequired = false;
  28785. };
  28786. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28787. if (this.object.getBoundingInfo) {
  28788. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28789. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28790. }
  28791. else {
  28792. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28793. }
  28794. };
  28795. PhysicsImpostor.prototype.getObjectCenter = function () {
  28796. if (this.object.getBoundingInfo) {
  28797. return this.object.getBoundingInfo().boundingBox.center;
  28798. }
  28799. else {
  28800. return this.object.position;
  28801. }
  28802. };
  28803. /**
  28804. * Get a specific parametes from the options parameter.
  28805. */
  28806. PhysicsImpostor.prototype.getParam = function (paramName) {
  28807. return this._options[paramName];
  28808. };
  28809. /**
  28810. * Sets a specific parameter in the options given to the physics plugin
  28811. */
  28812. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28813. this._options[paramName] = value;
  28814. this._bodyUpdateRequired = true;
  28815. };
  28816. /**
  28817. * Specifically change the body's mass option. Won't recreate the physics body object
  28818. */
  28819. PhysicsImpostor.prototype.setMass = function (mass) {
  28820. if (this.getParam("mass") !== mass) {
  28821. this.setParam("mass", mass);
  28822. }
  28823. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28824. };
  28825. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28826. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28827. };
  28828. /**
  28829. * Set the body's linear velocity.
  28830. */
  28831. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28832. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28833. };
  28834. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28835. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28836. };
  28837. /**
  28838. * Set the body's linear velocity.
  28839. */
  28840. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28841. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28842. };
  28843. /**
  28844. * Execute a function with the physics plugin native code.
  28845. * Provide a function the will have two variables - the world object and the physics body object.
  28846. */
  28847. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28848. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28849. };
  28850. /**
  28851. * Register a function that will be executed before the physics world is stepping forward.
  28852. */
  28853. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28854. this._onBeforePhysicsStepCallbacks.push(func);
  28855. };
  28856. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28857. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28858. if (index > -1) {
  28859. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28860. }
  28861. else {
  28862. BABYLON.Tools.Warn("Function to remove was not found");
  28863. }
  28864. };
  28865. /**
  28866. * Register a function that will be executed after the physics step
  28867. */
  28868. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28869. this._onAfterPhysicsStepCallbacks.push(func);
  28870. };
  28871. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28872. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28873. if (index > -1) {
  28874. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28875. }
  28876. else {
  28877. BABYLON.Tools.Warn("Function to remove was not found");
  28878. }
  28879. };
  28880. /**
  28881. * register a function that will be executed when this impostor collides against a different body.
  28882. */
  28883. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28884. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28885. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28886. };
  28887. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28888. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28889. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28890. if (index > -1) {
  28891. this._onPhysicsCollideCallbacks.splice(index, 1);
  28892. }
  28893. else {
  28894. BABYLON.Tools.Warn("Function to remove was not found");
  28895. }
  28896. };
  28897. /**
  28898. * Apply a force
  28899. */
  28900. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28901. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28902. };
  28903. /**
  28904. * Apply an impulse
  28905. */
  28906. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28907. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28908. };
  28909. /**
  28910. * A help function to create a joint.
  28911. */
  28912. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28913. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28914. this.addJoint(otherImpostor, joint);
  28915. };
  28916. /**
  28917. * Add a joint to this impostor with a different impostor.
  28918. */
  28919. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28920. this._joints.push({
  28921. otherImpostor: otherImpostor,
  28922. joint: joint
  28923. });
  28924. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28925. };
  28926. /**
  28927. * Will keep this body still, in a sleep mode.
  28928. */
  28929. PhysicsImpostor.prototype.sleep = function () {
  28930. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28931. };
  28932. /**
  28933. * Wake the body up.
  28934. */
  28935. PhysicsImpostor.prototype.wakeUp = function () {
  28936. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28937. };
  28938. PhysicsImpostor.prototype.clone = function (newObject) {
  28939. if (!newObject)
  28940. return null;
  28941. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28942. };
  28943. PhysicsImpostor.prototype.dispose = function () {
  28944. var _this = this;
  28945. //no dispose if no physics engine is available.
  28946. if (!this._physicsEngine) {
  28947. return;
  28948. }
  28949. this._joints.forEach(function (j) {
  28950. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  28951. });
  28952. //dispose the physics body
  28953. this._physicsEngine.removeImpostor(this);
  28954. if (this.parent) {
  28955. this.parent.forceUpdate();
  28956. }
  28957. else {
  28958. }
  28959. };
  28960. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  28961. this._deltaPosition.copyFrom(position);
  28962. };
  28963. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  28964. if (!this._deltaRotation) {
  28965. this._deltaRotation = new BABYLON.Quaternion();
  28966. }
  28967. this._deltaRotation.copyFrom(rotation);
  28968. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  28969. };
  28970. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  28971. //Impostor types
  28972. PhysicsImpostor.NoImpostor = 0;
  28973. PhysicsImpostor.SphereImpostor = 1;
  28974. PhysicsImpostor.BoxImpostor = 2;
  28975. PhysicsImpostor.PlaneImpostor = 3;
  28976. PhysicsImpostor.MeshImpostor = 4;
  28977. PhysicsImpostor.CylinderImpostor = 7;
  28978. PhysicsImpostor.ParticleImpostor = 8;
  28979. PhysicsImpostor.HeightmapImpostor = 9;
  28980. return PhysicsImpostor;
  28981. })();
  28982. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28983. })(BABYLON || (BABYLON = {}));
  28984. var BABYLON;
  28985. (function (BABYLON) {
  28986. var PhysicsEngine = (function () {
  28987. function PhysicsEngine(gravity, _physicsPlugin) {
  28988. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28989. this._physicsPlugin = _physicsPlugin;
  28990. //new methods and parameters
  28991. this._impostors = [];
  28992. this._joints = [];
  28993. if (!this._physicsPlugin.isSupported()) {
  28994. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28995. + "Please make sure it is included.");
  28996. }
  28997. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28998. this.setGravity(gravity);
  28999. this.setTimeStep();
  29000. }
  29001. PhysicsEngine.prototype.setGravity = function (gravity) {
  29002. this.gravity = gravity;
  29003. this._physicsPlugin.setGravity(this.gravity);
  29004. };
  29005. /**
  29006. * Set the time step of the physics engine.
  29007. * default is 1/60.
  29008. * To slow it down, enter 1/600 for example.
  29009. * To speed it up, 1/30
  29010. * @param {number} newTimeStep the new timestep to apply to this world.
  29011. */
  29012. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29013. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29014. this._physicsPlugin.setTimeStep(newTimeStep);
  29015. };
  29016. PhysicsEngine.prototype.dispose = function () {
  29017. this._impostors.forEach(function (impostor) {
  29018. impostor.dispose();
  29019. });
  29020. this._physicsPlugin.dispose();
  29021. };
  29022. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29023. return this._physicsPlugin.name;
  29024. };
  29025. /**
  29026. * Adding a new impostor for the impostor tracking.
  29027. * This will be done by the impostor itself.
  29028. * @param {PhysicsImpostor} impostor the impostor to add
  29029. */
  29030. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29031. impostor.uniqueId = this._impostors.push(impostor);
  29032. //if no parent, generate the body
  29033. if (!impostor.parent) {
  29034. this._physicsPlugin.generatePhysicsBody(impostor);
  29035. }
  29036. };
  29037. /**
  29038. * Remove an impostor from the engine.
  29039. * This impostor and its mesh will not longer be updated by the physics engine.
  29040. * @param {PhysicsImpostor} impostor the impostor to remove
  29041. */
  29042. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29043. var index = this._impostors.indexOf(impostor);
  29044. if (index > -1) {
  29045. var removed = this._impostors.splice(index, 1);
  29046. //Is it needed?
  29047. if (removed.length) {
  29048. //this will also remove it from the world.
  29049. removed[0].physicsBody = null;
  29050. }
  29051. }
  29052. };
  29053. /**
  29054. * Add a joint to the physics engine
  29055. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29056. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29057. * @param {PhysicsJoint} the joint that will connect both impostors.
  29058. */
  29059. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29060. var impostorJoint = {
  29061. mainImpostor: mainImpostor,
  29062. connectedImpostor: connectedImpostor,
  29063. joint: joint
  29064. };
  29065. joint.physicsPlugin = this._physicsPlugin;
  29066. this._joints.push(impostorJoint);
  29067. this._physicsPlugin.generateJoint(impostorJoint);
  29068. };
  29069. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29070. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29071. return (impostorJoint.connectedImpostor === connectedImpostor
  29072. && impostorJoint.joint === joint
  29073. && impostorJoint.mainImpostor === mainImpostor);
  29074. });
  29075. if (matchingJoints.length) {
  29076. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29077. }
  29078. };
  29079. /**
  29080. * Called by the scene. no need to call it.
  29081. */
  29082. PhysicsEngine.prototype._step = function (delta) {
  29083. var _this = this;
  29084. //check if any mesh has no body / requires an update
  29085. this._impostors.forEach(function (impostor) {
  29086. if (impostor.isBodyInitRequired()) {
  29087. _this._physicsPlugin.generatePhysicsBody(impostor);
  29088. }
  29089. });
  29090. if (delta > 0.1) {
  29091. delta = 0.1;
  29092. }
  29093. else if (delta <= 0) {
  29094. delta = 1.0 / 60.0;
  29095. }
  29096. this._physicsPlugin.executeStep(delta, this._impostors);
  29097. };
  29098. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29099. return this._physicsPlugin;
  29100. };
  29101. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29102. for (var i = 0; i < this._impostors.length; ++i) {
  29103. if (this._impostors[i].object === object) {
  29104. return this._impostors[i];
  29105. }
  29106. }
  29107. };
  29108. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29109. for (var i = 0; i < this._impostors.length; ++i) {
  29110. if (this._impostors[i].physicsBody === body) {
  29111. return this._impostors[i];
  29112. }
  29113. }
  29114. };
  29115. // Statics, Legacy support.
  29116. /**
  29117. * @Deprecated
  29118. *
  29119. */
  29120. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29121. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29122. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29123. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29124. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29125. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29126. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29127. PhysicsEngine.CapsuleImpostor = -1;
  29128. PhysicsEngine.ConeImpostor = -1;
  29129. PhysicsEngine.ConvexHullImpostor = -1;
  29130. PhysicsEngine.Epsilon = 0.001;
  29131. return PhysicsEngine;
  29132. })();
  29133. BABYLON.PhysicsEngine = PhysicsEngine;
  29134. })(BABYLON || (BABYLON = {}));
  29135. var BABYLON;
  29136. (function (BABYLON) {
  29137. var VertexData = (function () {
  29138. function VertexData() {
  29139. }
  29140. VertexData.prototype.set = function (data, kind) {
  29141. switch (kind) {
  29142. case BABYLON.VertexBuffer.PositionKind:
  29143. this.positions = data;
  29144. break;
  29145. case BABYLON.VertexBuffer.NormalKind:
  29146. this.normals = data;
  29147. break;
  29148. case BABYLON.VertexBuffer.UVKind:
  29149. this.uvs = data;
  29150. break;
  29151. case BABYLON.VertexBuffer.UV2Kind:
  29152. this.uvs2 = data;
  29153. break;
  29154. case BABYLON.VertexBuffer.UV3Kind:
  29155. this.uvs3 = data;
  29156. break;
  29157. case BABYLON.VertexBuffer.UV4Kind:
  29158. this.uvs4 = data;
  29159. break;
  29160. case BABYLON.VertexBuffer.UV5Kind:
  29161. this.uvs5 = data;
  29162. break;
  29163. case BABYLON.VertexBuffer.UV6Kind:
  29164. this.uvs6 = data;
  29165. break;
  29166. case BABYLON.VertexBuffer.ColorKind:
  29167. this.colors = data;
  29168. break;
  29169. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29170. this.matricesIndices = data;
  29171. break;
  29172. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29173. this.matricesWeights = data;
  29174. break;
  29175. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29176. this.matricesIndicesExtra = data;
  29177. break;
  29178. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29179. this.matricesWeightsExtra = data;
  29180. break;
  29181. }
  29182. };
  29183. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29184. this._applyTo(mesh, updatable);
  29185. };
  29186. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29187. this._applyTo(geometry, updatable);
  29188. };
  29189. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29190. this._update(mesh);
  29191. };
  29192. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29193. this._update(geometry);
  29194. };
  29195. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29196. if (this.positions) {
  29197. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29198. }
  29199. if (this.normals) {
  29200. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29201. }
  29202. if (this.uvs) {
  29203. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29204. }
  29205. if (this.uvs2) {
  29206. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29207. }
  29208. if (this.uvs3) {
  29209. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29210. }
  29211. if (this.uvs4) {
  29212. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29213. }
  29214. if (this.uvs5) {
  29215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29216. }
  29217. if (this.uvs6) {
  29218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29219. }
  29220. if (this.colors) {
  29221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29222. }
  29223. if (this.matricesIndices) {
  29224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29225. }
  29226. if (this.matricesWeights) {
  29227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29228. }
  29229. if (this.matricesIndicesExtra) {
  29230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29231. }
  29232. if (this.matricesWeightsExtra) {
  29233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29234. }
  29235. if (this.indices) {
  29236. meshOrGeometry.setIndices(this.indices);
  29237. }
  29238. };
  29239. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29240. if (this.positions) {
  29241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29242. }
  29243. if (this.normals) {
  29244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29245. }
  29246. if (this.uvs) {
  29247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29248. }
  29249. if (this.uvs2) {
  29250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29251. }
  29252. if (this.uvs3) {
  29253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29254. }
  29255. if (this.uvs4) {
  29256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29257. }
  29258. if (this.uvs5) {
  29259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29260. }
  29261. if (this.uvs6) {
  29262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29263. }
  29264. if (this.colors) {
  29265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29266. }
  29267. if (this.matricesIndices) {
  29268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29269. }
  29270. if (this.matricesWeights) {
  29271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29272. }
  29273. if (this.matricesIndicesExtra) {
  29274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29275. }
  29276. if (this.matricesWeightsExtra) {
  29277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29278. }
  29279. if (this.indices) {
  29280. meshOrGeometry.setIndices(this.indices);
  29281. }
  29282. };
  29283. VertexData.prototype.transform = function (matrix) {
  29284. var transformed = BABYLON.Vector3.Zero();
  29285. var index;
  29286. if (this.positions) {
  29287. var position = BABYLON.Vector3.Zero();
  29288. for (index = 0; index < this.positions.length; index += 3) {
  29289. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29290. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29291. this.positions[index] = transformed.x;
  29292. this.positions[index + 1] = transformed.y;
  29293. this.positions[index + 2] = transformed.z;
  29294. }
  29295. }
  29296. if (this.normals) {
  29297. var normal = BABYLON.Vector3.Zero();
  29298. for (index = 0; index < this.normals.length; index += 3) {
  29299. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29300. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29301. this.normals[index] = transformed.x;
  29302. this.normals[index + 1] = transformed.y;
  29303. this.normals[index + 2] = transformed.z;
  29304. }
  29305. }
  29306. };
  29307. VertexData.prototype.merge = function (other) {
  29308. if (other.indices) {
  29309. if (!this.indices) {
  29310. this.indices = [];
  29311. }
  29312. var offset = this.positions ? this.positions.length / 3 : 0;
  29313. for (var index = 0; index < other.indices.length; index++) {
  29314. //TODO check type - if Int32Array!
  29315. this.indices.push(other.indices[index] + offset);
  29316. }
  29317. }
  29318. this.positions = this._mergeElement(this.positions, other.positions);
  29319. this.normals = this._mergeElement(this.normals, other.normals);
  29320. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29321. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29322. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29323. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29324. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29325. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29326. this.colors = this._mergeElement(this.colors, other.colors);
  29327. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29328. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29329. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29330. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29331. };
  29332. VertexData.prototype._mergeElement = function (source, other) {
  29333. if (!other)
  29334. return source;
  29335. if (!source)
  29336. return other;
  29337. var len = other.length + source.length;
  29338. var isSrcTypedArray = source instanceof Float32Array;
  29339. var isOthTypedArray = other instanceof Float32Array;
  29340. // use non-loop method when the source is Float32Array
  29341. if (isSrcTypedArray) {
  29342. var ret32 = new Float32Array(len);
  29343. ret32.set(source);
  29344. ret32.set(other, source.length);
  29345. return ret32;
  29346. }
  29347. else if (!isOthTypedArray) {
  29348. return source.concat(other);
  29349. }
  29350. else {
  29351. var ret = source.slice(0); // copy source to a separate array
  29352. for (var i = 0, len = other.length; i < len; i++) {
  29353. ret.push(other[i]);
  29354. }
  29355. return ret;
  29356. }
  29357. };
  29358. VertexData.prototype.serialize = function () {
  29359. var serializationObject = this.serialize();
  29360. if (this.positions) {
  29361. serializationObject.positions = this.positions;
  29362. }
  29363. if (this.normals) {
  29364. serializationObject.normals = this.normals;
  29365. }
  29366. if (this.uvs) {
  29367. serializationObject.uvs = this.uvs;
  29368. }
  29369. if (this.uvs2) {
  29370. serializationObject.uvs2 = this.uvs2;
  29371. }
  29372. if (this.uvs3) {
  29373. serializationObject.uvs3 = this.uvs3;
  29374. }
  29375. if (this.uvs4) {
  29376. serializationObject.uvs4 = this.uvs4;
  29377. }
  29378. if (this.uvs5) {
  29379. serializationObject.uvs5 = this.uvs5;
  29380. }
  29381. if (this.uvs6) {
  29382. serializationObject.uvs6 = this.uvs6;
  29383. }
  29384. if (this.colors) {
  29385. serializationObject.colors = this.colors;
  29386. }
  29387. if (this.matricesIndices) {
  29388. serializationObject.matricesIndices = this.matricesIndices;
  29389. serializationObject.matricesIndices._isExpanded = true;
  29390. }
  29391. if (this.matricesWeights) {
  29392. serializationObject.matricesWeights = this.matricesWeights;
  29393. }
  29394. if (this.matricesIndicesExtra) {
  29395. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29396. serializationObject.matricesIndicesExtra._isExpanded = true;
  29397. }
  29398. if (this.matricesWeightsExtra) {
  29399. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29400. }
  29401. serializationObject.indices = this.indices;
  29402. return serializationObject;
  29403. };
  29404. // Statics
  29405. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29406. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29407. };
  29408. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29409. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29410. };
  29411. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29412. var result = new VertexData();
  29413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29414. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29415. }
  29416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29417. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29418. }
  29419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29420. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29421. }
  29422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29423. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29424. }
  29425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29426. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29427. }
  29428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29429. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29430. }
  29431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29432. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29433. }
  29434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29435. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29436. }
  29437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29438. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29439. }
  29440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29441. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29442. }
  29443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29444. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29445. }
  29446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29447. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29448. }
  29449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29450. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29451. }
  29452. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29453. return result;
  29454. };
  29455. VertexData.CreateRibbon = function (options) {
  29456. var pathArray = options.pathArray;
  29457. var closeArray = options.closeArray || false;
  29458. var closePath = options.closePath || false;
  29459. var invertUV = options.invertUV || false;
  29460. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29461. var offset = options.offset || defaultOffset;
  29462. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29463. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29464. var positions = [];
  29465. var indices = [];
  29466. var normals = [];
  29467. var uvs = [];
  29468. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29469. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29470. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29471. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29472. var minlg; // minimal length among all paths from pathArray
  29473. var lg = []; // array of path lengths : nb of vertex per path
  29474. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29475. var p; // path iterator
  29476. var i; // point iterator
  29477. var j; // point iterator
  29478. // if single path in pathArray
  29479. if (pathArray.length < 2) {
  29480. var ar1 = [];
  29481. var ar2 = [];
  29482. for (i = 0; i < pathArray[0].length - offset; i++) {
  29483. ar1.push(pathArray[0][i]);
  29484. ar2.push(pathArray[0][i + offset]);
  29485. }
  29486. pathArray = [ar1, ar2];
  29487. }
  29488. // positions and horizontal distances (u)
  29489. var idc = 0;
  29490. var closePathCorr = (closePath) ? 1 : 0;
  29491. var path;
  29492. var l;
  29493. minlg = pathArray[0].length;
  29494. var vectlg;
  29495. var dist;
  29496. for (p = 0; p < pathArray.length; p++) {
  29497. uTotalDistance[p] = 0;
  29498. us[p] = [0];
  29499. path = pathArray[p];
  29500. l = path.length;
  29501. minlg = (minlg < l) ? minlg : l;
  29502. j = 0;
  29503. while (j < l) {
  29504. positions.push(path[j].x, path[j].y, path[j].z);
  29505. if (j > 0) {
  29506. vectlg = path[j].subtract(path[j - 1]).length();
  29507. dist = vectlg + uTotalDistance[p];
  29508. us[p].push(dist);
  29509. uTotalDistance[p] = dist;
  29510. }
  29511. j++;
  29512. }
  29513. if (closePath) {
  29514. j--;
  29515. positions.push(path[0].x, path[0].y, path[0].z);
  29516. vectlg = path[j].subtract(path[0]).length();
  29517. dist = vectlg + uTotalDistance[p];
  29518. us[p].push(dist);
  29519. uTotalDistance[p] = dist;
  29520. }
  29521. lg[p] = l + closePathCorr;
  29522. idx[p] = idc;
  29523. idc += (l + closePathCorr);
  29524. }
  29525. // vertical distances (v)
  29526. var path1;
  29527. var path2;
  29528. var vertex1;
  29529. var vertex2;
  29530. for (i = 0; i < minlg + closePathCorr; i++) {
  29531. vTotalDistance[i] = 0;
  29532. vs[i] = [0];
  29533. for (p = 0; p < pathArray.length - 1; p++) {
  29534. path1 = pathArray[p];
  29535. path2 = pathArray[p + 1];
  29536. if (i === minlg) {
  29537. vertex1 = path1[0];
  29538. vertex2 = path2[0];
  29539. }
  29540. else {
  29541. vertex1 = path1[i];
  29542. vertex2 = path2[i];
  29543. }
  29544. vectlg = vertex2.subtract(vertex1).length();
  29545. dist = vectlg + vTotalDistance[i];
  29546. vs[i].push(dist);
  29547. vTotalDistance[i] = dist;
  29548. }
  29549. if (closeArray) {
  29550. path1 = pathArray[p];
  29551. path2 = pathArray[0];
  29552. if (i === minlg) {
  29553. vertex2 = path2[0];
  29554. }
  29555. vectlg = vertex2.subtract(vertex1).length();
  29556. dist = vectlg + vTotalDistance[i];
  29557. vTotalDistance[i] = dist;
  29558. }
  29559. }
  29560. // uvs
  29561. var u;
  29562. var v;
  29563. for (p = 0; p < pathArray.length; p++) {
  29564. for (i = 0; i < minlg + closePathCorr; i++) {
  29565. u = us[p][i] / uTotalDistance[p];
  29566. v = vs[i][p] / vTotalDistance[i];
  29567. if (invertUV) {
  29568. uvs.push(v, u);
  29569. }
  29570. else {
  29571. uvs.push(u, v);
  29572. }
  29573. }
  29574. }
  29575. // indices
  29576. p = 0; // path index
  29577. var pi = 0; // positions array index
  29578. var l1 = lg[p] - 1; // path1 length
  29579. var l2 = lg[p + 1] - 1; // path2 length
  29580. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29581. var shft = idx[1] - idx[0]; // shift
  29582. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29583. while (pi <= min && p < path1nb) {
  29584. // 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
  29585. indices.push(pi, pi + shft, pi + 1);
  29586. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29587. pi += 1;
  29588. if (pi === min) {
  29589. p++;
  29590. if (p === lg.length - 1) {
  29591. shft = idx[0] - idx[p];
  29592. l1 = lg[p] - 1;
  29593. l2 = lg[0] - 1;
  29594. }
  29595. else {
  29596. shft = idx[p + 1] - idx[p];
  29597. l1 = lg[p] - 1;
  29598. l2 = lg[p + 1] - 1;
  29599. }
  29600. pi = idx[p];
  29601. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29602. }
  29603. }
  29604. // normals
  29605. VertexData.ComputeNormals(positions, indices, normals);
  29606. if (closePath) {
  29607. var indexFirst = 0;
  29608. var indexLast = 0;
  29609. for (p = 0; p < pathArray.length; p++) {
  29610. indexFirst = idx[p] * 3;
  29611. if (p + 1 < pathArray.length) {
  29612. indexLast = (idx[p + 1] - 1) * 3;
  29613. }
  29614. else {
  29615. indexLast = normals.length - 3;
  29616. }
  29617. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29618. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29619. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29620. normals[indexLast] = normals[indexFirst];
  29621. normals[indexLast + 1] = normals[indexFirst + 1];
  29622. normals[indexLast + 2] = normals[indexFirst + 2];
  29623. }
  29624. }
  29625. // sides
  29626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29627. // Result
  29628. var vertexData = new VertexData();
  29629. vertexData.indices = indices;
  29630. vertexData.positions = positions;
  29631. vertexData.normals = normals;
  29632. vertexData.uvs = uvs;
  29633. if (closePath) {
  29634. vertexData._idx = idx;
  29635. }
  29636. return vertexData;
  29637. };
  29638. VertexData.CreateBox = function (options) {
  29639. var normalsSource = [
  29640. new BABYLON.Vector3(0, 0, 1),
  29641. new BABYLON.Vector3(0, 0, -1),
  29642. new BABYLON.Vector3(1, 0, 0),
  29643. new BABYLON.Vector3(-1, 0, 0),
  29644. new BABYLON.Vector3(0, 1, 0),
  29645. new BABYLON.Vector3(0, -1, 0)
  29646. ];
  29647. var indices = [];
  29648. var positions = [];
  29649. var normals = [];
  29650. var uvs = [];
  29651. var width = options.width || options.size || 1;
  29652. var height = options.height || options.size || 1;
  29653. var depth = options.depth || options.size || 1;
  29654. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29655. var faceUV = options.faceUV || new Array(6);
  29656. var faceColors = options.faceColors;
  29657. var colors = [];
  29658. // default face colors and UV if undefined
  29659. for (var f = 0; f < 6; f++) {
  29660. if (faceUV[f] === undefined) {
  29661. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29662. }
  29663. if (faceColors && faceColors[f] === undefined) {
  29664. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29665. }
  29666. }
  29667. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29668. // Create each face in turn.
  29669. for (var index = 0; index < normalsSource.length; index++) {
  29670. var normal = normalsSource[index];
  29671. // Get two vectors perpendicular to the face normal and to each other.
  29672. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29673. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29674. // Six indices (two triangles) per face.
  29675. var verticesLength = positions.length / 3;
  29676. indices.push(verticesLength);
  29677. indices.push(verticesLength + 1);
  29678. indices.push(verticesLength + 2);
  29679. indices.push(verticesLength);
  29680. indices.push(verticesLength + 2);
  29681. indices.push(verticesLength + 3);
  29682. // Four vertices per face.
  29683. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29684. positions.push(vertex.x, vertex.y, vertex.z);
  29685. normals.push(normal.x, normal.y, normal.z);
  29686. uvs.push(faceUV[index].z, faceUV[index].w);
  29687. if (faceColors) {
  29688. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29689. }
  29690. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29691. positions.push(vertex.x, vertex.y, vertex.z);
  29692. normals.push(normal.x, normal.y, normal.z);
  29693. uvs.push(faceUV[index].x, faceUV[index].w);
  29694. if (faceColors) {
  29695. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29696. }
  29697. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29698. positions.push(vertex.x, vertex.y, vertex.z);
  29699. normals.push(normal.x, normal.y, normal.z);
  29700. uvs.push(faceUV[index].x, faceUV[index].y);
  29701. if (faceColors) {
  29702. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29703. }
  29704. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29705. positions.push(vertex.x, vertex.y, vertex.z);
  29706. normals.push(normal.x, normal.y, normal.z);
  29707. uvs.push(faceUV[index].z, faceUV[index].y);
  29708. if (faceColors) {
  29709. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29710. }
  29711. }
  29712. // sides
  29713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29714. // Result
  29715. var vertexData = new VertexData();
  29716. vertexData.indices = indices;
  29717. vertexData.positions = positions;
  29718. vertexData.normals = normals;
  29719. vertexData.uvs = uvs;
  29720. if (faceColors) {
  29721. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29722. vertexData.colors = totalColors;
  29723. }
  29724. return vertexData;
  29725. };
  29726. VertexData.CreateSphere = function (options) {
  29727. var segments = options.segments || 32;
  29728. var diameterX = options.diameterX || options.diameter || 1;
  29729. var diameterY = options.diameterY || options.diameter || 1;
  29730. var diameterZ = options.diameterZ || options.diameter || 1;
  29731. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29732. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29734. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29735. var totalZRotationSteps = 2 + segments;
  29736. var totalYRotationSteps = 2 * totalZRotationSteps;
  29737. var indices = [];
  29738. var positions = [];
  29739. var normals = [];
  29740. var uvs = [];
  29741. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29742. var normalizedZ = zRotationStep / totalZRotationSteps;
  29743. var angleZ = normalizedZ * Math.PI * slice;
  29744. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29745. var normalizedY = yRotationStep / totalYRotationSteps;
  29746. var angleY = normalizedY * Math.PI * 2 * arc;
  29747. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29748. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29749. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29750. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29751. var vertex = complete.multiply(radius);
  29752. var normal = complete.divide(radius).normalize();
  29753. positions.push(vertex.x, vertex.y, vertex.z);
  29754. normals.push(normal.x, normal.y, normal.z);
  29755. uvs.push(normalizedY, normalizedZ);
  29756. }
  29757. if (zRotationStep > 0) {
  29758. var verticesCount = positions.length / 3;
  29759. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29760. indices.push((firstIndex));
  29761. indices.push((firstIndex + 1));
  29762. indices.push(firstIndex + totalYRotationSteps + 1);
  29763. indices.push((firstIndex + totalYRotationSteps + 1));
  29764. indices.push((firstIndex + 1));
  29765. indices.push((firstIndex + totalYRotationSteps + 2));
  29766. }
  29767. }
  29768. }
  29769. // Sides
  29770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29771. // Result
  29772. var vertexData = new VertexData();
  29773. vertexData.indices = indices;
  29774. vertexData.positions = positions;
  29775. vertexData.normals = normals;
  29776. vertexData.uvs = uvs;
  29777. return vertexData;
  29778. };
  29779. // Cylinder and cone
  29780. VertexData.CreateCylinder = function (options) {
  29781. var height = options.height || 2;
  29782. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29783. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29784. var tessellation = options.tessellation || 24;
  29785. var subdivisions = options.subdivisions || 1;
  29786. var hasRings = options.hasRings;
  29787. var enclose = options.enclose;
  29788. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29789. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29790. var faceUV = options.faceUV || new Array(3);
  29791. var faceColors = options.faceColors;
  29792. // default face colors and UV if undefined
  29793. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29794. var ringNb = (hasRings) ? subdivisions : 1;
  29795. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29796. var f;
  29797. for (f = 0; f < surfaceNb; f++) {
  29798. if (faceColors && faceColors[f] === undefined) {
  29799. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29800. }
  29801. }
  29802. for (f = 0; f < surfaceNb; f++) {
  29803. if (faceUV && faceUV[f] === undefined) {
  29804. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29805. }
  29806. }
  29807. var indices = [];
  29808. var positions = [];
  29809. var normals = [];
  29810. var uvs = [];
  29811. var colors = [];
  29812. var angle_step = Math.PI * 2 * arc / tessellation;
  29813. var angle;
  29814. var h;
  29815. var radius;
  29816. var tan = (diameterBottom - diameterTop) / 2 / height;
  29817. var ringVertex = BABYLON.Vector3.Zero();
  29818. var ringNormal = BABYLON.Vector3.Zero();
  29819. var ringFirstVertex = BABYLON.Vector3.Zero();
  29820. var ringFirstNormal = BABYLON.Vector3.Zero();
  29821. var quadNormal = BABYLON.Vector3.Zero();
  29822. var Y = BABYLON.Axis.Y;
  29823. // positions, normals, uvs
  29824. var i;
  29825. var j;
  29826. var r;
  29827. var ringIdx = 1;
  29828. var s = 1; // surface index
  29829. var cs = 0;
  29830. var v = 0;
  29831. for (i = 0; i <= subdivisions; i++) {
  29832. h = i / subdivisions;
  29833. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29834. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29835. for (r = 0; r < ringIdx; r++) {
  29836. if (hasRings) {
  29837. s += r;
  29838. }
  29839. if (enclose) {
  29840. s += 2 * r;
  29841. }
  29842. for (j = 0; j <= tessellation; j++) {
  29843. angle = j * angle_step;
  29844. // position
  29845. ringVertex.x = Math.cos(-angle) * radius;
  29846. ringVertex.y = -height / 2 + h * height;
  29847. ringVertex.z = Math.sin(-angle) * radius;
  29848. // normal
  29849. if (diameterTop === 0 && i === subdivisions) {
  29850. // if no top cap, reuse former normals
  29851. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29852. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29853. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29854. }
  29855. else {
  29856. ringNormal.x = ringVertex.x;
  29857. ringNormal.z = ringVertex.z;
  29858. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29859. ringNormal.normalize();
  29860. }
  29861. // keep first ring vertex values for enclose
  29862. if (j === 0) {
  29863. ringFirstVertex.copyFrom(ringVertex);
  29864. ringFirstNormal.copyFrom(ringNormal);
  29865. }
  29866. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29867. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29868. if (hasRings) {
  29869. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29870. }
  29871. else {
  29872. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29873. }
  29874. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29875. if (faceColors) {
  29876. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29877. }
  29878. }
  29879. // if enclose, add four vertices and their dedicated normals
  29880. if (arc !== 1 && enclose) {
  29881. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29882. positions.push(0, ringVertex.y, 0);
  29883. positions.push(0, ringVertex.y, 0);
  29884. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29885. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29886. quadNormal.normalize();
  29887. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29888. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29889. quadNormal.normalize();
  29890. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29891. if (hasRings) {
  29892. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29893. }
  29894. else {
  29895. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29896. }
  29897. uvs.push(faceUV[s + 1].x, v);
  29898. uvs.push(faceUV[s + 1].z, v);
  29899. if (hasRings) {
  29900. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29901. }
  29902. else {
  29903. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29904. }
  29905. uvs.push(faceUV[s + 2].x, v);
  29906. uvs.push(faceUV[s + 2].z, v);
  29907. if (faceColors) {
  29908. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29909. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29910. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29911. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29912. }
  29913. }
  29914. if (cs !== s) {
  29915. cs = s;
  29916. }
  29917. }
  29918. }
  29919. // indices
  29920. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29921. var s;
  29922. i = 0;
  29923. for (s = 0; s < subdivisions; s++) {
  29924. for (j = 0; j < tessellation; j++) {
  29925. var i0 = i * (e + 1) + j;
  29926. var i1 = (i + 1) * (e + 1) + j;
  29927. var i2 = i * (e + 1) + (j + 1);
  29928. var i3 = (i + 1) * (e + 1) + (j + 1);
  29929. indices.push(i0, i1, i2);
  29930. indices.push(i3, i2, i1);
  29931. }
  29932. if (arc !== 1 && enclose) {
  29933. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29934. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29935. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29936. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29937. }
  29938. i = (hasRings) ? (i + 2) : (i + 1);
  29939. }
  29940. // Caps
  29941. var createCylinderCap = function (isTop) {
  29942. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29943. if (radius === 0) {
  29944. return;
  29945. }
  29946. // Cap positions, normals & uvs
  29947. var angle;
  29948. var circleVector;
  29949. var i;
  29950. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29951. var c;
  29952. if (faceColors) {
  29953. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29954. }
  29955. // cap center
  29956. var vbase = positions.length / 3;
  29957. var offset = isTop ? height / 2 : -height / 2;
  29958. var center = new BABYLON.Vector3(0, offset, 0);
  29959. positions.push(center.x, center.y, center.z);
  29960. normals.push(0, isTop ? 1 : -1, 0);
  29961. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29962. if (faceColors) {
  29963. colors.push(c.r, c.g, c.b, c.a);
  29964. }
  29965. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29966. for (i = 0; i <= tessellation; i++) {
  29967. angle = Math.PI * 2 * i * arc / tessellation;
  29968. var cos = Math.cos(-angle);
  29969. var sin = Math.sin(-angle);
  29970. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29971. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29972. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29973. normals.push(0, isTop ? 1 : -1, 0);
  29974. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29975. if (faceColors) {
  29976. colors.push(c.r, c.g, c.b, c.a);
  29977. }
  29978. }
  29979. // Cap indices
  29980. for (i = 0; i < tessellation; i++) {
  29981. if (!isTop) {
  29982. indices.push(vbase);
  29983. indices.push(vbase + (i + 1));
  29984. indices.push(vbase + (i + 2));
  29985. }
  29986. else {
  29987. indices.push(vbase);
  29988. indices.push(vbase + (i + 2));
  29989. indices.push(vbase + (i + 1));
  29990. }
  29991. }
  29992. };
  29993. // add caps to geometry
  29994. createCylinderCap(false);
  29995. createCylinderCap(true);
  29996. // Sides
  29997. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29998. var vertexData = new VertexData();
  29999. vertexData.indices = indices;
  30000. vertexData.positions = positions;
  30001. vertexData.normals = normals;
  30002. vertexData.uvs = uvs;
  30003. if (faceColors) {
  30004. vertexData.colors = colors;
  30005. }
  30006. return vertexData;
  30007. };
  30008. VertexData.CreateTorus = function (options) {
  30009. var indices = [];
  30010. var positions = [];
  30011. var normals = [];
  30012. var uvs = [];
  30013. var diameter = options.diameter || 1;
  30014. var thickness = options.thickness || 0.5;
  30015. var tessellation = options.tessellation || 16;
  30016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30017. var stride = tessellation + 1;
  30018. for (var i = 0; i <= tessellation; i++) {
  30019. var u = i / tessellation;
  30020. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30021. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30022. for (var j = 0; j <= tessellation; j++) {
  30023. var v = 1 - j / tessellation;
  30024. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30025. var dx = Math.cos(innerAngle);
  30026. var dy = Math.sin(innerAngle);
  30027. // Create a vertex.
  30028. var normal = new BABYLON.Vector3(dx, dy, 0);
  30029. var position = normal.scale(thickness / 2);
  30030. var textureCoordinate = new BABYLON.Vector2(u, v);
  30031. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30032. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30033. positions.push(position.x, position.y, position.z);
  30034. normals.push(normal.x, normal.y, normal.z);
  30035. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30036. // And create indices for two triangles.
  30037. var nextI = (i + 1) % stride;
  30038. var nextJ = (j + 1) % stride;
  30039. indices.push(i * stride + j);
  30040. indices.push(i * stride + nextJ);
  30041. indices.push(nextI * stride + j);
  30042. indices.push(i * stride + nextJ);
  30043. indices.push(nextI * stride + nextJ);
  30044. indices.push(nextI * stride + j);
  30045. }
  30046. }
  30047. // Sides
  30048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30049. // Result
  30050. var vertexData = new VertexData();
  30051. vertexData.indices = indices;
  30052. vertexData.positions = positions;
  30053. vertexData.normals = normals;
  30054. vertexData.uvs = uvs;
  30055. return vertexData;
  30056. };
  30057. VertexData.CreateLineSystem = function (options) {
  30058. var indices = [];
  30059. var positions = [];
  30060. var lines = options.lines;
  30061. var idx = 0;
  30062. for (var l = 0; l < lines.length; l++) {
  30063. var points = lines[l];
  30064. for (var index = 0; index < points.length; index++) {
  30065. positions.push(points[index].x, points[index].y, points[index].z);
  30066. if (index > 0) {
  30067. indices.push(idx - 1);
  30068. indices.push(idx);
  30069. }
  30070. idx++;
  30071. }
  30072. }
  30073. var vertexData = new VertexData();
  30074. vertexData.indices = indices;
  30075. vertexData.positions = positions;
  30076. return vertexData;
  30077. };
  30078. VertexData.CreateDashedLines = function (options) {
  30079. var dashSize = options.dashSize || 3;
  30080. var gapSize = options.gapSize || 1;
  30081. var dashNb = options.dashNb || 200;
  30082. var points = options.points;
  30083. var positions = new Array();
  30084. var indices = new Array();
  30085. var curvect = BABYLON.Vector3.Zero();
  30086. var lg = 0;
  30087. var nb = 0;
  30088. var shft = 0;
  30089. var dashshft = 0;
  30090. var curshft = 0;
  30091. var idx = 0;
  30092. var i = 0;
  30093. for (i = 0; i < points.length - 1; i++) {
  30094. points[i + 1].subtractToRef(points[i], curvect);
  30095. lg += curvect.length();
  30096. }
  30097. shft = lg / dashNb;
  30098. dashshft = dashSize * shft / (dashSize + gapSize);
  30099. for (i = 0; i < points.length - 1; i++) {
  30100. points[i + 1].subtractToRef(points[i], curvect);
  30101. nb = Math.floor(curvect.length() / shft);
  30102. curvect.normalize();
  30103. for (var j = 0; j < nb; j++) {
  30104. curshft = shft * j;
  30105. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30106. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30107. indices.push(idx, idx + 1);
  30108. idx += 2;
  30109. }
  30110. }
  30111. // Result
  30112. var vertexData = new VertexData();
  30113. vertexData.positions = positions;
  30114. vertexData.indices = indices;
  30115. return vertexData;
  30116. };
  30117. VertexData.CreateGround = function (options) {
  30118. var indices = [];
  30119. var positions = [];
  30120. var normals = [];
  30121. var uvs = [];
  30122. var row, col;
  30123. var width = options.width || 1;
  30124. var height = options.height || 1;
  30125. var subdivisions = options.subdivisions || 1;
  30126. for (row = 0; row <= subdivisions; row++) {
  30127. for (col = 0; col <= subdivisions; col++) {
  30128. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30129. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30130. positions.push(position.x, position.y, position.z);
  30131. normals.push(normal.x, normal.y, normal.z);
  30132. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30133. }
  30134. }
  30135. for (row = 0; row < subdivisions; row++) {
  30136. for (col = 0; col < subdivisions; col++) {
  30137. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30138. indices.push(col + 1 + row * (subdivisions + 1));
  30139. indices.push(col + row * (subdivisions + 1));
  30140. indices.push(col + (row + 1) * (subdivisions + 1));
  30141. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30142. indices.push(col + row * (subdivisions + 1));
  30143. }
  30144. }
  30145. // Result
  30146. var vertexData = new VertexData();
  30147. vertexData.indices = indices;
  30148. vertexData.positions = positions;
  30149. vertexData.normals = normals;
  30150. vertexData.uvs = uvs;
  30151. return vertexData;
  30152. };
  30153. VertexData.CreateTiledGround = function (options) {
  30154. var xmin = options.xmin || -1.0;
  30155. var zmin = options.zmin || -1.0;
  30156. var xmax = options.xmax || 1.0;
  30157. var zmax = options.zmax || 1.0;
  30158. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30159. var precision = options.precision || { w: 1, h: 1 };
  30160. var indices = [];
  30161. var positions = [];
  30162. var normals = [];
  30163. var uvs = [];
  30164. var row, col, tileRow, tileCol;
  30165. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30166. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30167. precision.w = (precision.w < 1) ? 1 : precision.w;
  30168. precision.h = (precision.h < 1) ? 1 : precision.h;
  30169. var tileSize = {
  30170. 'w': (xmax - xmin) / subdivisions.w,
  30171. 'h': (zmax - zmin) / subdivisions.h
  30172. };
  30173. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30174. // Indices
  30175. var base = positions.length / 3;
  30176. var rowLength = precision.w + 1;
  30177. for (row = 0; row < precision.h; row++) {
  30178. for (col = 0; col < precision.w; col++) {
  30179. var square = [
  30180. base + col + row * rowLength,
  30181. base + (col + 1) + row * rowLength,
  30182. base + (col + 1) + (row + 1) * rowLength,
  30183. base + col + (row + 1) * rowLength
  30184. ];
  30185. indices.push(square[1]);
  30186. indices.push(square[2]);
  30187. indices.push(square[3]);
  30188. indices.push(square[0]);
  30189. indices.push(square[1]);
  30190. indices.push(square[3]);
  30191. }
  30192. }
  30193. // Position, normals and uvs
  30194. var position = BABYLON.Vector3.Zero();
  30195. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30196. for (row = 0; row <= precision.h; row++) {
  30197. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30198. for (col = 0; col <= precision.w; col++) {
  30199. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30200. position.y = 0;
  30201. positions.push(position.x, position.y, position.z);
  30202. normals.push(normal.x, normal.y, normal.z);
  30203. uvs.push(col / precision.w, row / precision.h);
  30204. }
  30205. }
  30206. }
  30207. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30208. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30209. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30210. }
  30211. }
  30212. // Result
  30213. var vertexData = new VertexData();
  30214. vertexData.indices = indices;
  30215. vertexData.positions = positions;
  30216. vertexData.normals = normals;
  30217. vertexData.uvs = uvs;
  30218. return vertexData;
  30219. };
  30220. VertexData.CreateGroundFromHeightMap = function (options) {
  30221. var indices = [];
  30222. var positions = [];
  30223. var normals = [];
  30224. var uvs = [];
  30225. var row, col;
  30226. // Vertices
  30227. for (row = 0; row <= options.subdivisions; row++) {
  30228. for (col = 0; col <= options.subdivisions; col++) {
  30229. 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));
  30230. // Compute height
  30231. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30232. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30233. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30234. var r = options.buffer[pos] / 255.0;
  30235. var g = options.buffer[pos + 1] / 255.0;
  30236. var b = options.buffer[pos + 2] / 255.0;
  30237. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30238. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30239. // Add vertex
  30240. positions.push(position.x, position.y, position.z);
  30241. normals.push(0, 0, 0);
  30242. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30243. }
  30244. }
  30245. // Indices
  30246. for (row = 0; row < options.subdivisions; row++) {
  30247. for (col = 0; col < options.subdivisions; col++) {
  30248. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30249. indices.push(col + 1 + row * (options.subdivisions + 1));
  30250. indices.push(col + row * (options.subdivisions + 1));
  30251. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30252. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30253. indices.push(col + row * (options.subdivisions + 1));
  30254. }
  30255. }
  30256. // Normals
  30257. VertexData.ComputeNormals(positions, indices, normals);
  30258. // Result
  30259. var vertexData = new VertexData();
  30260. vertexData.indices = indices;
  30261. vertexData.positions = positions;
  30262. vertexData.normals = normals;
  30263. vertexData.uvs = uvs;
  30264. return vertexData;
  30265. };
  30266. VertexData.CreatePlane = function (options) {
  30267. var indices = [];
  30268. var positions = [];
  30269. var normals = [];
  30270. var uvs = [];
  30271. var width = options.width || options.size || 1;
  30272. var height = options.height || options.size || 1;
  30273. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30274. // Vertices
  30275. var halfWidth = width / 2.0;
  30276. var halfHeight = height / 2.0;
  30277. positions.push(-halfWidth, -halfHeight, 0);
  30278. normals.push(0, 0, -1.0);
  30279. uvs.push(0.0, 0.0);
  30280. positions.push(halfWidth, -halfHeight, 0);
  30281. normals.push(0, 0, -1.0);
  30282. uvs.push(1.0, 0.0);
  30283. positions.push(halfWidth, halfHeight, 0);
  30284. normals.push(0, 0, -1.0);
  30285. uvs.push(1.0, 1.0);
  30286. positions.push(-halfWidth, halfHeight, 0);
  30287. normals.push(0, 0, -1.0);
  30288. uvs.push(0.0, 1.0);
  30289. // Indices
  30290. indices.push(0);
  30291. indices.push(1);
  30292. indices.push(2);
  30293. indices.push(0);
  30294. indices.push(2);
  30295. indices.push(3);
  30296. // Sides
  30297. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30298. // Result
  30299. var vertexData = new VertexData();
  30300. vertexData.indices = indices;
  30301. vertexData.positions = positions;
  30302. vertexData.normals = normals;
  30303. vertexData.uvs = uvs;
  30304. return vertexData;
  30305. };
  30306. VertexData.CreateDisc = function (options) {
  30307. var positions = [];
  30308. var indices = [];
  30309. var normals = [];
  30310. var uvs = [];
  30311. var radius = options.radius || 0.5;
  30312. var tessellation = options.tessellation || 64;
  30313. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30314. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30315. // positions and uvs
  30316. positions.push(0, 0, 0); // disc center first
  30317. uvs.push(0.5, 0.5);
  30318. var theta = Math.PI * 2 * arc;
  30319. var step = theta / tessellation;
  30320. for (var a = 0; a < theta; a += step) {
  30321. var x = Math.cos(a);
  30322. var y = Math.sin(a);
  30323. var u = (x + 1) / 2;
  30324. var v = (1 - y) / 2;
  30325. positions.push(radius * x, radius * y, 0);
  30326. uvs.push(u, v);
  30327. }
  30328. if (arc === 1) {
  30329. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30330. uvs.push(uvs[2], uvs[3]);
  30331. }
  30332. //indices
  30333. var vertexNb = positions.length / 3;
  30334. for (var i = 1; i < vertexNb - 1; i++) {
  30335. indices.push(i + 1, 0, i);
  30336. }
  30337. // result
  30338. VertexData.ComputeNormals(positions, indices, normals);
  30339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30340. var vertexData = new VertexData();
  30341. vertexData.indices = indices;
  30342. vertexData.positions = positions;
  30343. vertexData.normals = normals;
  30344. vertexData.uvs = uvs;
  30345. return vertexData;
  30346. };
  30347. VertexData.CreateIcoSphere = function (options) {
  30348. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30349. var radius = options.radius || 1;
  30350. var flat = (options.flat === undefined) ? true : options.flat;
  30351. var subdivisions = options.subdivisions || 4;
  30352. var radiusX = options.radiusX || radius;
  30353. var radiusY = options.radiusY || radius;
  30354. var radiusZ = options.radiusZ || radius;
  30355. var t = (1 + Math.sqrt(5)) / 2;
  30356. // 12 vertex x,y,z
  30357. var ico_vertices = [
  30358. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30359. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30360. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30361. ];
  30362. // index of 3 vertex makes a face of icopshere
  30363. var ico_indices = [
  30364. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30365. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30366. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30367. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30368. ];
  30369. // vertex for uv have aliased position, not for UV
  30370. var vertices_unalias_id = [
  30371. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30372. // vertex alias
  30373. 0,
  30374. 2,
  30375. 3,
  30376. 3,
  30377. 3,
  30378. 4,
  30379. 7,
  30380. 8,
  30381. 9,
  30382. 9,
  30383. 10,
  30384. 11 // 23: B + 12
  30385. ];
  30386. // uv as integer step (not pixels !)
  30387. var ico_vertexuv = [
  30388. 5, 1, 3, 1, 6, 4, 0, 0,
  30389. 5, 3, 4, 2, 2, 2, 4, 0,
  30390. 2, 0, 1, 1, 6, 0, 6, 2,
  30391. // vertex alias (for same vertex on different faces)
  30392. 0, 4,
  30393. 3, 3,
  30394. 4, 4,
  30395. 3, 1,
  30396. 4, 2,
  30397. 4, 4,
  30398. 0, 2,
  30399. 1, 1,
  30400. 2, 2,
  30401. 3, 3,
  30402. 1, 3,
  30403. 2, 4 // 23: B + 12
  30404. ];
  30405. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30406. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30407. // First island of uv mapping
  30408. // v = 4h 3+ 2
  30409. // v = 3h 9+ 4
  30410. // v = 2h 9+ 5 B
  30411. // v = 1h 9 1 0
  30412. // v = 0h 3 8 7 A
  30413. // u = 0 1 2 3 4 5 6 *a
  30414. // Second island of uv mapping
  30415. // v = 4h 0+ B+ 4+
  30416. // v = 3h A+ 2+
  30417. // v = 2h 7+ 6 3+
  30418. // v = 1h 8+ 3+
  30419. // v = 0h
  30420. // u = 0 1 2 3 4 5 6 *a
  30421. // Face layout on texture UV mapping
  30422. // ============
  30423. // \ 4 /\ 16 / ======
  30424. // \ / \ / /\ 11 /
  30425. // \/ 7 \/ / \ /
  30426. // ======= / 10 \/
  30427. // /\ 17 /\ =======
  30428. // / \ / \ \ 15 /\
  30429. // / 8 \/ 12 \ \ / \
  30430. // ============ \/ 6 \
  30431. // \ 18 /\ ============
  30432. // \ / \ \ 5 /\ 0 /
  30433. // \/ 13 \ \ / \ /
  30434. // ======= \/ 1 \/
  30435. // =============
  30436. // /\ 19 /\ 2 /\
  30437. // / \ / \ / \
  30438. // / 14 \/ 9 \/ 3 \
  30439. // ===================
  30440. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30441. var ustep = 138 / 1024;
  30442. var vstep = 239 / 1024;
  30443. var uoffset = 60 / 1024;
  30444. var voffset = 26 / 1024;
  30445. // Second island should have margin, not to touch the first island
  30446. // avoid any borderline artefact in pixel rounding
  30447. var island_u_offset = -40 / 1024;
  30448. var island_v_offset = +20 / 1024;
  30449. // face is either island 0 or 1 :
  30450. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30451. var island = [
  30452. 0, 0, 0, 0, 1,
  30453. 0, 0, 1, 1, 0,
  30454. 0, 0, 1, 1, 0,
  30455. 0, 1, 1, 1, 0 // 15 - 19
  30456. ];
  30457. var indices = [];
  30458. var positions = [];
  30459. var normals = [];
  30460. var uvs = [];
  30461. var current_indice = 0;
  30462. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30463. var face_vertex_pos = new Array(3);
  30464. var face_vertex_uv = new Array(3);
  30465. var v012;
  30466. for (v012 = 0; v012 < 3; v012++) {
  30467. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30468. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30469. }
  30470. // create all with normals
  30471. for (var face = 0; face < 20; face++) {
  30472. // 3 vertex per face
  30473. for (v012 = 0; v012 < 3; v012++) {
  30474. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30475. var v_id = ico_indices[3 * face + v012];
  30476. // vertex have 3D position (x,y,z)
  30477. 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]);
  30478. // Normalize to get normal, then scale to radius
  30479. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30480. // uv Coordinates from vertex ID
  30481. 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);
  30482. }
  30483. // Subdivide the face (interpolate pos, norm, uv)
  30484. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30485. // - norm is linear interpolation of vertex corner normal
  30486. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30487. // - uv is linear interpolation
  30488. //
  30489. // Topology is as below for sub-divide by 2
  30490. // vertex shown as v0,v1,v2
  30491. // interp index is i1 to progress in range [v0,v1[
  30492. // interp index is i2 to progress in range [v0,v2[
  30493. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30494. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30495. //
  30496. //
  30497. // i2 v2
  30498. // ^ ^
  30499. // / / \
  30500. // / / \
  30501. // / / \
  30502. // / / (0,1) \
  30503. // / #---------\
  30504. // / / \ (0,0)'/ \
  30505. // / / \ / \
  30506. // / / \ / \
  30507. // / / (0,0) \ / (1,0) \
  30508. // / #---------#---------\
  30509. // v0 v1
  30510. //
  30511. // --------------------> i1
  30512. //
  30513. // interp of (i1,i2):
  30514. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30515. // along i1 : lerp(x0,x1, i1/(S-i2))
  30516. //
  30517. // centroid of triangle is needed to get help normal computation
  30518. // (c1,c2) are used for centroid location
  30519. var interp_vertex = function (i1, i2, c1, c2) {
  30520. // vertex is interpolated from
  30521. // - face_vertex_pos[0..2]
  30522. // - face_vertex_uv[0..2]
  30523. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30524. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30525. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30526. pos_interp.normalize();
  30527. var vertex_normal;
  30528. if (flat) {
  30529. // in flat mode, recalculate normal as face centroid normal
  30530. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30531. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30532. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30533. }
  30534. else {
  30535. // in smooth mode, recalculate normal from each single vertex position
  30536. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30537. }
  30538. // Vertex normal need correction due to X,Y,Z radius scaling
  30539. vertex_normal.x /= radiusX;
  30540. vertex_normal.y /= radiusY;
  30541. vertex_normal.z /= radiusZ;
  30542. vertex_normal.normalize();
  30543. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30544. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30545. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30546. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30547. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30548. uvs.push(uv_interp.x, uv_interp.y);
  30549. // push each vertex has member of a face
  30550. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30551. indices.push(current_indice);
  30552. current_indice++;
  30553. };
  30554. for (var i2 = 0; i2 < subdivisions; i2++) {
  30555. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30556. // face : (i1,i2) for /\ :
  30557. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30558. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30559. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30560. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30561. if (i1 + i2 + 1 < subdivisions) {
  30562. // face : (i1,i2)' for \/ :
  30563. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30564. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30565. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30566. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30567. }
  30568. }
  30569. }
  30570. }
  30571. // Sides
  30572. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30573. // Result
  30574. var vertexData = new VertexData();
  30575. vertexData.indices = indices;
  30576. vertexData.positions = positions;
  30577. vertexData.normals = normals;
  30578. vertexData.uvs = uvs;
  30579. return vertexData;
  30580. };
  30581. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30582. VertexData.CreatePolyhedron = function (options) {
  30583. // provided polyhedron types :
  30584. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30585. // 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)
  30586. var polyhedra = [];
  30587. 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]] };
  30588. 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]] };
  30589. polyhedra[2] = {
  30590. 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]],
  30591. 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]]
  30592. };
  30593. polyhedra[3] = {
  30594. 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]],
  30595. 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]]
  30596. };
  30597. polyhedra[4] = {
  30598. 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]],
  30599. 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]]
  30600. };
  30601. 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]] };
  30602. 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]] };
  30603. 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]] };
  30604. 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]] };
  30605. 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]] };
  30606. 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]] };
  30607. 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]] };
  30608. 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]] };
  30609. 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]] };
  30610. polyhedra[14] = {
  30611. 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]],
  30612. 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]]
  30613. };
  30614. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30615. var size = options.size;
  30616. var sizeX = options.sizeX || size || 1;
  30617. var sizeY = options.sizeY || size || 1;
  30618. var sizeZ = options.sizeZ || size || 1;
  30619. var data = options.custom || polyhedra[type];
  30620. var nbfaces = data.face.length;
  30621. var faceUV = options.faceUV || new Array(nbfaces);
  30622. var faceColors = options.faceColors;
  30623. var flat = (options.flat === undefined) ? true : options.flat;
  30624. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30625. var positions = [];
  30626. var indices = [];
  30627. var normals = [];
  30628. var uvs = [];
  30629. var colors = [];
  30630. var index = 0;
  30631. var faceIdx = 0; // face cursor in the array "indexes"
  30632. var indexes = [];
  30633. var i = 0;
  30634. var f = 0;
  30635. var u, v, ang, x, y, tmp;
  30636. // default face colors and UV if undefined
  30637. if (flat) {
  30638. for (f = 0; f < nbfaces; f++) {
  30639. if (faceColors && faceColors[f] === undefined) {
  30640. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30641. }
  30642. if (faceUV && faceUV[f] === undefined) {
  30643. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30644. }
  30645. }
  30646. }
  30647. if (!flat) {
  30648. for (i = 0; i < data.vertex.length; i++) {
  30649. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30650. uvs.push(0, 0);
  30651. }
  30652. for (f = 0; f < nbfaces; f++) {
  30653. for (i = 0; i < data.face[f].length - 2; i++) {
  30654. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30655. }
  30656. }
  30657. }
  30658. else {
  30659. for (f = 0; f < nbfaces; f++) {
  30660. var fl = data.face[f].length; // number of vertices of the current face
  30661. ang = 2 * Math.PI / fl;
  30662. x = 0.5 * Math.tan(ang / 2);
  30663. y = 0.5;
  30664. // positions, uvs, colors
  30665. for (i = 0; i < fl; i++) {
  30666. // positions
  30667. 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);
  30668. indexes.push(index);
  30669. index++;
  30670. // uvs
  30671. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30672. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30673. uvs.push(u, v);
  30674. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30675. y = x * Math.sin(ang) + y * Math.cos(ang);
  30676. x = tmp;
  30677. // colors
  30678. if (faceColors) {
  30679. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30680. }
  30681. }
  30682. // indices from indexes
  30683. for (i = 0; i < fl - 2; i++) {
  30684. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30685. }
  30686. faceIdx += fl;
  30687. }
  30688. }
  30689. VertexData.ComputeNormals(positions, indices, normals);
  30690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30691. var vertexData = new VertexData();
  30692. vertexData.positions = positions;
  30693. vertexData.indices = indices;
  30694. vertexData.normals = normals;
  30695. vertexData.uvs = uvs;
  30696. if (faceColors && flat) {
  30697. vertexData.colors = colors;
  30698. }
  30699. return vertexData;
  30700. };
  30701. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30702. VertexData.CreateTorusKnot = function (options) {
  30703. var indices = [];
  30704. var positions = [];
  30705. var normals = [];
  30706. var uvs = [];
  30707. var radius = options.radius || 2;
  30708. var tube = options.tube || 0.5;
  30709. var radialSegments = options.radialSegments || 32;
  30710. var tubularSegments = options.tubularSegments || 32;
  30711. var p = options.p || 2;
  30712. var q = options.q || 3;
  30713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30714. // Helper
  30715. var getPos = function (angle) {
  30716. var cu = Math.cos(angle);
  30717. var su = Math.sin(angle);
  30718. var quOverP = q / p * angle;
  30719. var cs = Math.cos(quOverP);
  30720. var tx = radius * (2 + cs) * 0.5 * cu;
  30721. var ty = radius * (2 + cs) * su * 0.5;
  30722. var tz = radius * Math.sin(quOverP) * 0.5;
  30723. return new BABYLON.Vector3(tx, ty, tz);
  30724. };
  30725. // Vertices
  30726. var i;
  30727. var j;
  30728. for (i = 0; i <= radialSegments; i++) {
  30729. var modI = i % radialSegments;
  30730. var u = modI / radialSegments * 2 * p * Math.PI;
  30731. var p1 = getPos(u);
  30732. var p2 = getPos(u + 0.01);
  30733. var tang = p2.subtract(p1);
  30734. var n = p2.add(p1);
  30735. var bitan = BABYLON.Vector3.Cross(tang, n);
  30736. n = BABYLON.Vector3.Cross(bitan, tang);
  30737. bitan.normalize();
  30738. n.normalize();
  30739. for (j = 0; j < tubularSegments; j++) {
  30740. var modJ = j % tubularSegments;
  30741. var v = modJ / tubularSegments * 2 * Math.PI;
  30742. var cx = -tube * Math.cos(v);
  30743. var cy = tube * Math.sin(v);
  30744. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30745. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30746. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30747. uvs.push(i / radialSegments);
  30748. uvs.push(j / tubularSegments);
  30749. }
  30750. }
  30751. for (i = 0; i < radialSegments; i++) {
  30752. for (j = 0; j < tubularSegments; j++) {
  30753. var jNext = (j + 1) % tubularSegments;
  30754. var a = i * tubularSegments + j;
  30755. var b = (i + 1) * tubularSegments + j;
  30756. var c = (i + 1) * tubularSegments + jNext;
  30757. var d = i * tubularSegments + jNext;
  30758. indices.push(d);
  30759. indices.push(b);
  30760. indices.push(a);
  30761. indices.push(d);
  30762. indices.push(c);
  30763. indices.push(b);
  30764. }
  30765. }
  30766. // Normals
  30767. VertexData.ComputeNormals(positions, indices, normals);
  30768. // Sides
  30769. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30770. // Result
  30771. var vertexData = new VertexData();
  30772. vertexData.indices = indices;
  30773. vertexData.positions = positions;
  30774. vertexData.normals = normals;
  30775. vertexData.uvs = uvs;
  30776. return vertexData;
  30777. };
  30778. // Tools
  30779. /**
  30780. * @param {any} - positions (number[] or Float32Array)
  30781. * @param {any} - indices (number[] or Uint16Array)
  30782. * @param {any} - normals (number[] or Float32Array)
  30783. */
  30784. VertexData.ComputeNormals = function (positions, indices, normals) {
  30785. var index = 0;
  30786. var p1p2x = 0.0;
  30787. var p1p2y = 0.0;
  30788. var p1p2z = 0.0;
  30789. var p3p2x = 0.0;
  30790. var p3p2y = 0.0;
  30791. var p3p2z = 0.0;
  30792. var faceNormalx = 0.0;
  30793. var faceNormaly = 0.0;
  30794. var faceNormalz = 0.0;
  30795. var length = 0.0;
  30796. var i1 = 0;
  30797. var i2 = 0;
  30798. var i3 = 0;
  30799. for (index = 0; index < positions.length; index++) {
  30800. normals[index] = 0.0;
  30801. }
  30802. // indice triplet = 1 face
  30803. var nbFaces = indices.length / 3;
  30804. for (index = 0; index < nbFaces; index++) {
  30805. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30806. i2 = indices[index * 3 + 1];
  30807. i3 = indices[index * 3 + 2];
  30808. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30809. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30810. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30811. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30812. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30813. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30814. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30815. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30816. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30817. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30818. length = (length === 0) ? 1.0 : length;
  30819. faceNormalx /= length; // normalize this normal
  30820. faceNormaly /= length;
  30821. faceNormalz /= length;
  30822. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30823. normals[i1 * 3 + 1] += faceNormaly;
  30824. normals[i1 * 3 + 2] += faceNormalz;
  30825. normals[i2 * 3] += faceNormalx;
  30826. normals[i2 * 3 + 1] += faceNormaly;
  30827. normals[i2 * 3 + 2] += faceNormalz;
  30828. normals[i3 * 3] += faceNormalx;
  30829. normals[i3 * 3 + 1] += faceNormaly;
  30830. normals[i3 * 3 + 2] += faceNormalz;
  30831. }
  30832. // last normalization of each normal
  30833. for (index = 0; index < normals.length / 3; index++) {
  30834. faceNormalx = normals[index * 3];
  30835. faceNormaly = normals[index * 3 + 1];
  30836. faceNormalz = normals[index * 3 + 2];
  30837. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30838. length = (length === 0) ? 1.0 : length;
  30839. faceNormalx /= length;
  30840. faceNormaly /= length;
  30841. faceNormalz /= length;
  30842. normals[index * 3] = faceNormalx;
  30843. normals[index * 3 + 1] = faceNormaly;
  30844. normals[index * 3 + 2] = faceNormalz;
  30845. }
  30846. };
  30847. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30848. var li = indices.length;
  30849. var ln = normals.length;
  30850. var i;
  30851. var n;
  30852. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30853. switch (sideOrientation) {
  30854. case BABYLON.Mesh.FRONTSIDE:
  30855. // nothing changed
  30856. break;
  30857. case BABYLON.Mesh.BACKSIDE:
  30858. var tmp;
  30859. // indices
  30860. for (i = 0; i < li; i += 3) {
  30861. tmp = indices[i];
  30862. indices[i] = indices[i + 2];
  30863. indices[i + 2] = tmp;
  30864. }
  30865. // normals
  30866. for (n = 0; n < ln; n++) {
  30867. normals[n] = -normals[n];
  30868. }
  30869. break;
  30870. case BABYLON.Mesh.DOUBLESIDE:
  30871. // positions
  30872. var lp = positions.length;
  30873. var l = lp / 3;
  30874. for (var p = 0; p < lp; p++) {
  30875. positions[lp + p] = positions[p];
  30876. }
  30877. // indices
  30878. for (i = 0; i < li; i += 3) {
  30879. indices[i + li] = indices[i + 2] + l;
  30880. indices[i + 1 + li] = indices[i + 1] + l;
  30881. indices[i + 2 + li] = indices[i] + l;
  30882. }
  30883. // normals
  30884. for (n = 0; n < ln; n++) {
  30885. normals[ln + n] = -normals[n];
  30886. }
  30887. // uvs
  30888. var lu = uvs.length;
  30889. for (var u = 0; u < lu; u++) {
  30890. uvs[u + lu] = uvs[u];
  30891. }
  30892. break;
  30893. }
  30894. };
  30895. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30896. var vertexData = new VertexData();
  30897. // positions
  30898. var positions = parsedVertexData.positions;
  30899. if (positions) {
  30900. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30901. }
  30902. // normals
  30903. var normals = parsedVertexData.normals;
  30904. if (normals) {
  30905. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30906. }
  30907. // uvs
  30908. var uvs = parsedVertexData.uvs;
  30909. if (uvs) {
  30910. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30911. }
  30912. // uv2s
  30913. var uv2s = parsedVertexData.uv2s;
  30914. if (uv2s) {
  30915. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30916. }
  30917. // uv3s
  30918. var uv3s = parsedVertexData.uv3s;
  30919. if (uv3s) {
  30920. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30921. }
  30922. // uv4s
  30923. var uv4s = parsedVertexData.uv4s;
  30924. if (uv4s) {
  30925. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30926. }
  30927. // uv5s
  30928. var uv5s = parsedVertexData.uv5s;
  30929. if (uv5s) {
  30930. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30931. }
  30932. // uv6s
  30933. var uv6s = parsedVertexData.uv6s;
  30934. if (uv6s) {
  30935. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30936. }
  30937. // colors
  30938. var colors = parsedVertexData.colors;
  30939. if (colors) {
  30940. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30941. }
  30942. // matricesIndices
  30943. var matricesIndices = parsedVertexData.matricesIndices;
  30944. if (matricesIndices) {
  30945. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30946. }
  30947. // matricesWeights
  30948. var matricesWeights = parsedVertexData.matricesWeights;
  30949. if (matricesWeights) {
  30950. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30951. }
  30952. // indices
  30953. var indices = parsedVertexData.indices;
  30954. if (indices) {
  30955. vertexData.indices = indices;
  30956. }
  30957. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30958. };
  30959. return VertexData;
  30960. })();
  30961. BABYLON.VertexData = VertexData;
  30962. })(BABYLON || (BABYLON = {}));
  30963. var BABYLON;
  30964. (function (BABYLON) {
  30965. var Tags = (function () {
  30966. function Tags() {
  30967. }
  30968. Tags.EnableFor = function (obj) {
  30969. obj._tags = obj._tags || {};
  30970. obj.hasTags = function () {
  30971. return Tags.HasTags(obj);
  30972. };
  30973. obj.addTags = function (tagsString) {
  30974. return Tags.AddTagsTo(obj, tagsString);
  30975. };
  30976. obj.removeTags = function (tagsString) {
  30977. return Tags.RemoveTagsFrom(obj, tagsString);
  30978. };
  30979. obj.matchesTagsQuery = function (tagsQuery) {
  30980. return Tags.MatchesQuery(obj, tagsQuery);
  30981. };
  30982. };
  30983. Tags.DisableFor = function (obj) {
  30984. delete obj._tags;
  30985. delete obj.hasTags;
  30986. delete obj.addTags;
  30987. delete obj.removeTags;
  30988. delete obj.matchesTagsQuery;
  30989. };
  30990. Tags.HasTags = function (obj) {
  30991. if (!obj._tags) {
  30992. return false;
  30993. }
  30994. return !BABYLON.Tools.IsEmpty(obj._tags);
  30995. };
  30996. Tags.GetTags = function (obj, asString) {
  30997. if (asString === void 0) { asString = true; }
  30998. if (!obj._tags) {
  30999. return null;
  31000. }
  31001. if (asString) {
  31002. var tagsArray = [];
  31003. for (var tag in obj._tags) {
  31004. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31005. tagsArray.push(tag);
  31006. }
  31007. }
  31008. return tagsArray.join(" ");
  31009. }
  31010. else {
  31011. return obj._tags;
  31012. }
  31013. };
  31014. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31015. // a tag cannot start with '||', '&&', and '!'
  31016. // it cannot contain whitespaces
  31017. Tags.AddTagsTo = function (obj, tagsString) {
  31018. if (!tagsString) {
  31019. return;
  31020. }
  31021. if (typeof tagsString !== "string") {
  31022. return;
  31023. }
  31024. var tags = tagsString.split(" ");
  31025. for (var t in tags) {
  31026. Tags._AddTagTo(obj, tags[t]);
  31027. }
  31028. };
  31029. Tags._AddTagTo = function (obj, tag) {
  31030. tag = tag.trim();
  31031. if (tag === "" || tag === "true" || tag === "false") {
  31032. return;
  31033. }
  31034. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31035. return;
  31036. }
  31037. Tags.EnableFor(obj);
  31038. obj._tags[tag] = true;
  31039. };
  31040. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31041. if (!Tags.HasTags(obj)) {
  31042. return;
  31043. }
  31044. var tags = tagsString.split(" ");
  31045. for (var t in tags) {
  31046. Tags._RemoveTagFrom(obj, tags[t]);
  31047. }
  31048. };
  31049. Tags._RemoveTagFrom = function (obj, tag) {
  31050. delete obj._tags[tag];
  31051. };
  31052. Tags.MatchesQuery = function (obj, tagsQuery) {
  31053. if (tagsQuery === undefined) {
  31054. return true;
  31055. }
  31056. if (tagsQuery === "") {
  31057. return Tags.HasTags(obj);
  31058. }
  31059. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31060. };
  31061. return Tags;
  31062. })();
  31063. BABYLON.Tags = Tags;
  31064. })(BABYLON || (BABYLON = {}));
  31065. var BABYLON;
  31066. (function (BABYLON) {
  31067. var Internals;
  31068. (function (Internals) {
  31069. var AndOrNotEvaluator = (function () {
  31070. function AndOrNotEvaluator() {
  31071. }
  31072. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31073. if (!query.match(/\([^\(\)]*\)/g)) {
  31074. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31075. }
  31076. else {
  31077. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31078. // remove parenthesis
  31079. r = r.slice(1, r.length - 1);
  31080. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31081. });
  31082. }
  31083. if (query === "true") {
  31084. return true;
  31085. }
  31086. if (query === "false") {
  31087. return false;
  31088. }
  31089. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31090. };
  31091. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31092. evaluateCallback = evaluateCallback || (function (r) {
  31093. return r === "true" ? true : false;
  31094. });
  31095. var result;
  31096. var or = parenthesisContent.split("||");
  31097. for (var i in or) {
  31098. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31099. var and = ori.split("&&");
  31100. if (and.length > 1) {
  31101. for (var j = 0; j < and.length; ++j) {
  31102. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31103. if (andj !== "true" && andj !== "false") {
  31104. if (andj[0] === "!") {
  31105. result = !evaluateCallback(andj.substring(1));
  31106. }
  31107. else {
  31108. result = evaluateCallback(andj);
  31109. }
  31110. }
  31111. else {
  31112. result = andj === "true" ? true : false;
  31113. }
  31114. if (!result) {
  31115. ori = "false";
  31116. break;
  31117. }
  31118. }
  31119. }
  31120. if (result || ori === "true") {
  31121. result = true;
  31122. break;
  31123. }
  31124. // result equals false (or undefined)
  31125. if (ori !== "true" && ori !== "false") {
  31126. if (ori[0] === "!") {
  31127. result = !evaluateCallback(ori.substring(1));
  31128. }
  31129. else {
  31130. result = evaluateCallback(ori);
  31131. }
  31132. }
  31133. else {
  31134. result = ori === "true" ? true : false;
  31135. }
  31136. }
  31137. // the whole parenthesis scope is replaced by 'true' or 'false'
  31138. return result ? "true" : "false";
  31139. };
  31140. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31141. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31142. // remove whitespaces
  31143. r = r.replace(/[\s]/g, function () { return ""; });
  31144. return r.length % 2 ? "!" : "";
  31145. });
  31146. booleanString = booleanString.trim();
  31147. if (booleanString === "!true") {
  31148. booleanString = "false";
  31149. }
  31150. else if (booleanString === "!false") {
  31151. booleanString = "true";
  31152. }
  31153. return booleanString;
  31154. };
  31155. return AndOrNotEvaluator;
  31156. })();
  31157. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31158. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31159. })(BABYLON || (BABYLON = {}));
  31160. var BABYLON;
  31161. (function (BABYLON) {
  31162. var PostProcessRenderPass = (function () {
  31163. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31164. this._enabled = true;
  31165. this._refCount = 0;
  31166. this._name = name;
  31167. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31168. this.setRenderList(renderList);
  31169. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31170. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31171. this._scene = scene;
  31172. this._renderList = renderList;
  31173. }
  31174. // private
  31175. PostProcessRenderPass.prototype._incRefCount = function () {
  31176. if (this._refCount === 0) {
  31177. this._scene.customRenderTargets.push(this._renderTexture);
  31178. }
  31179. return ++this._refCount;
  31180. };
  31181. PostProcessRenderPass.prototype._decRefCount = function () {
  31182. this._refCount--;
  31183. if (this._refCount <= 0) {
  31184. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31185. }
  31186. return this._refCount;
  31187. };
  31188. PostProcessRenderPass.prototype._update = function () {
  31189. this.setRenderList(this._renderList);
  31190. };
  31191. // public
  31192. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31193. this._renderTexture.renderList = renderList;
  31194. };
  31195. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31196. return this._renderTexture;
  31197. };
  31198. return PostProcessRenderPass;
  31199. })();
  31200. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31201. })(BABYLON || (BABYLON = {}));
  31202. var BABYLON;
  31203. (function (BABYLON) {
  31204. var PostProcessRenderEffect = (function () {
  31205. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31206. this._engine = engine;
  31207. this._name = name;
  31208. this._singleInstance = singleInstance || true;
  31209. this._getPostProcess = getPostProcess;
  31210. this._cameras = [];
  31211. this._indicesForCamera = [];
  31212. this._postProcesses = {};
  31213. this._renderPasses = {};
  31214. this._renderEffectAsPasses = {};
  31215. }
  31216. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31217. get: function () {
  31218. for (var index in this._postProcesses) {
  31219. if (!this._postProcesses[index].isSupported) {
  31220. return false;
  31221. }
  31222. }
  31223. return true;
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. PostProcessRenderEffect.prototype._update = function () {
  31229. for (var renderPassName in this._renderPasses) {
  31230. this._renderPasses[renderPassName]._update();
  31231. }
  31232. };
  31233. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31234. this._renderPasses[renderPass._name] = renderPass;
  31235. this._linkParameters();
  31236. };
  31237. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31238. delete this._renderPasses[renderPass._name];
  31239. this._linkParameters();
  31240. };
  31241. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31242. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31243. this._linkParameters();
  31244. };
  31245. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31246. for (var renderPassName in this._renderPasses) {
  31247. if (renderPassName === passName) {
  31248. return this._renderPasses[passName];
  31249. }
  31250. }
  31251. };
  31252. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31253. this._renderPasses = {};
  31254. this._linkParameters();
  31255. };
  31256. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31257. var cameraKey;
  31258. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31259. for (var i = 0; i < _cam.length; i++) {
  31260. var camera = _cam[i];
  31261. var cameraName = camera.name;
  31262. if (this._singleInstance) {
  31263. cameraKey = 0;
  31264. }
  31265. else {
  31266. cameraKey = cameraName;
  31267. }
  31268. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31269. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31270. if (!this._indicesForCamera[cameraName]) {
  31271. this._indicesForCamera[cameraName] = [];
  31272. }
  31273. this._indicesForCamera[cameraName].push(index);
  31274. if (this._cameras.indexOf(camera) === -1) {
  31275. this._cameras[cameraName] = camera;
  31276. }
  31277. for (var passName in this._renderPasses) {
  31278. this._renderPasses[passName]._incRefCount();
  31279. }
  31280. }
  31281. this._linkParameters();
  31282. };
  31283. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31284. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31285. for (var i = 0; i < _cam.length; i++) {
  31286. var camera = _cam[i];
  31287. var cameraName = camera.name;
  31288. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31289. var index = this._cameras.indexOf(cameraName);
  31290. this._indicesForCamera.splice(index, 1);
  31291. this._cameras.splice(index, 1);
  31292. for (var passName in this._renderPasses) {
  31293. this._renderPasses[passName]._decRefCount();
  31294. }
  31295. }
  31296. };
  31297. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31298. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31299. for (var i = 0; i < _cam.length; i++) {
  31300. var camera = _cam[i];
  31301. var cameraName = camera.name;
  31302. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31303. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31304. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31305. }
  31306. }
  31307. for (var passName in this._renderPasses) {
  31308. this._renderPasses[passName]._incRefCount();
  31309. }
  31310. }
  31311. };
  31312. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31314. for (var i = 0; i < _cam.length; i++) {
  31315. var camera = _cam[i];
  31316. var cameraName = camera.Name;
  31317. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31318. for (var passName in this._renderPasses) {
  31319. this._renderPasses[passName]._decRefCount();
  31320. }
  31321. }
  31322. };
  31323. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31324. if (this._singleInstance) {
  31325. return this._postProcesses[0];
  31326. }
  31327. else {
  31328. return this._postProcesses[camera.name];
  31329. }
  31330. };
  31331. PostProcessRenderEffect.prototype._linkParameters = function () {
  31332. var _this = this;
  31333. for (var index in this._postProcesses) {
  31334. if (this.applyParameters) {
  31335. this.applyParameters(this._postProcesses[index]);
  31336. }
  31337. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31338. _this._linkTextures(effect);
  31339. });
  31340. }
  31341. };
  31342. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31343. for (var renderPassName in this._renderPasses) {
  31344. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31345. }
  31346. for (var renderEffectName in this._renderEffectAsPasses) {
  31347. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31348. }
  31349. };
  31350. return PostProcessRenderEffect;
  31351. })();
  31352. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31353. })(BABYLON || (BABYLON = {}));
  31354. var BABYLON;
  31355. (function (BABYLON) {
  31356. var PostProcessRenderPipeline = (function () {
  31357. function PostProcessRenderPipeline(engine, name) {
  31358. this._engine = engine;
  31359. this._name = name;
  31360. this._renderEffects = {};
  31361. this._renderEffectsForIsolatedPass = {};
  31362. this._cameras = [];
  31363. }
  31364. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31365. get: function () {
  31366. for (var renderEffectName in this._renderEffects) {
  31367. if (!this._renderEffects[renderEffectName].isSupported) {
  31368. return false;
  31369. }
  31370. }
  31371. return true;
  31372. },
  31373. enumerable: true,
  31374. configurable: true
  31375. });
  31376. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31377. this._renderEffects[renderEffect._name] = renderEffect;
  31378. };
  31379. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31380. var renderEffects = this._renderEffects[renderEffectName];
  31381. if (!renderEffects) {
  31382. return;
  31383. }
  31384. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31385. };
  31386. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31387. var renderEffects = this._renderEffects[renderEffectName];
  31388. if (!renderEffects) {
  31389. return;
  31390. }
  31391. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31392. };
  31393. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31394. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31395. var indicesToDelete = [];
  31396. var i;
  31397. for (i = 0; i < _cam.length; i++) {
  31398. var camera = _cam[i];
  31399. var cameraName = camera.name;
  31400. if (this._cameras.indexOf(camera) === -1) {
  31401. this._cameras[cameraName] = camera;
  31402. }
  31403. else if (unique) {
  31404. indicesToDelete.push(i);
  31405. }
  31406. }
  31407. for (i = 0; i < indicesToDelete.length; i++) {
  31408. cameras.splice(indicesToDelete[i], 1);
  31409. }
  31410. for (var renderEffectName in this._renderEffects) {
  31411. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31412. }
  31413. };
  31414. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31415. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31416. for (var renderEffectName in this._renderEffects) {
  31417. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31418. }
  31419. for (var i = 0; i < _cam.length; i++) {
  31420. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31421. }
  31422. };
  31423. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31424. var _this = this;
  31425. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31426. var pass = null;
  31427. var renderEffectName;
  31428. for (renderEffectName in this._renderEffects) {
  31429. pass = this._renderEffects[renderEffectName].getPass(passName);
  31430. if (pass != null) {
  31431. break;
  31432. }
  31433. }
  31434. if (pass === null) {
  31435. return;
  31436. }
  31437. for (renderEffectName in this._renderEffects) {
  31438. this._renderEffects[renderEffectName]._disable(_cam);
  31439. }
  31440. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31441. for (var i = 0; i < _cam.length; i++) {
  31442. var camera = _cam[i];
  31443. var cameraName = camera.name;
  31444. 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); });
  31445. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31446. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31447. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31448. }
  31449. };
  31450. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31451. var _this = this;
  31452. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31453. for (var i = 0; i < _cam.length; i++) {
  31454. var camera = _cam[i];
  31455. var cameraName = camera.name;
  31456. 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); });
  31457. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31458. }
  31459. for (var renderEffectName in this._renderEffects) {
  31460. this._renderEffects[renderEffectName]._enable(_cam);
  31461. }
  31462. };
  31463. PostProcessRenderPipeline.prototype._update = function () {
  31464. for (var renderEffectName in this._renderEffects) {
  31465. this._renderEffects[renderEffectName]._update();
  31466. }
  31467. for (var i = 0; i < this._cameras.length; i++) {
  31468. var cameraName = this._cameras[i].name;
  31469. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31470. this._renderEffectsForIsolatedPass[cameraName]._update();
  31471. }
  31472. }
  31473. };
  31474. PostProcessRenderPipeline.prototype.dispose = function () {
  31475. // Must be implemented by children
  31476. };
  31477. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31478. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31479. return PostProcessRenderPipeline;
  31480. })();
  31481. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31482. })(BABYLON || (BABYLON = {}));
  31483. var BABYLON;
  31484. (function (BABYLON) {
  31485. var PostProcessRenderPipelineManager = (function () {
  31486. function PostProcessRenderPipelineManager() {
  31487. this._renderPipelines = {};
  31488. }
  31489. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31490. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31491. };
  31492. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31493. var renderPipeline = this._renderPipelines[renderPipelineName];
  31494. if (!renderPipeline) {
  31495. return;
  31496. }
  31497. renderPipeline._attachCameras(cameras, unique);
  31498. };
  31499. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31500. var renderPipeline = this._renderPipelines[renderPipelineName];
  31501. if (!renderPipeline) {
  31502. return;
  31503. }
  31504. renderPipeline._detachCameras(cameras);
  31505. };
  31506. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31507. var renderPipeline = this._renderPipelines[renderPipelineName];
  31508. if (!renderPipeline) {
  31509. return;
  31510. }
  31511. renderPipeline._enableEffect(renderEffectName, cameras);
  31512. };
  31513. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31514. var renderPipeline = this._renderPipelines[renderPipelineName];
  31515. if (!renderPipeline) {
  31516. return;
  31517. }
  31518. renderPipeline._disableEffect(renderEffectName, cameras);
  31519. };
  31520. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31521. var renderPipeline = this._renderPipelines[renderPipelineName];
  31522. if (!renderPipeline) {
  31523. return;
  31524. }
  31525. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31526. };
  31527. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31528. var renderPipeline = this._renderPipelines[renderPipelineName];
  31529. if (!renderPipeline) {
  31530. return;
  31531. }
  31532. renderPipeline._disableDisplayOnlyPass(cameras);
  31533. };
  31534. PostProcessRenderPipelineManager.prototype.update = function () {
  31535. for (var renderPipelineName in this._renderPipelines) {
  31536. var pipeline = this._renderPipelines[renderPipelineName];
  31537. if (!pipeline.isSupported) {
  31538. pipeline.dispose();
  31539. delete this._renderPipelines[renderPipelineName];
  31540. }
  31541. else {
  31542. pipeline._update();
  31543. }
  31544. }
  31545. };
  31546. return PostProcessRenderPipelineManager;
  31547. })();
  31548. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31549. })(BABYLON || (BABYLON = {}));
  31550. var BABYLON;
  31551. (function (BABYLON) {
  31552. var BoundingBoxRenderer = (function () {
  31553. function BoundingBoxRenderer(scene) {
  31554. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31555. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31556. this.showBackLines = true;
  31557. this.renderList = new BABYLON.SmartArray(32);
  31558. this._vertexBuffers = {};
  31559. this._scene = scene;
  31560. }
  31561. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31562. if (this._colorShader) {
  31563. return;
  31564. }
  31565. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31566. attributes: [BABYLON.VertexBuffer.PositionKind],
  31567. uniforms: ["worldViewProjection", "color"]
  31568. });
  31569. var engine = this._scene.getEngine();
  31570. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31572. 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]);
  31573. };
  31574. BoundingBoxRenderer.prototype.reset = function () {
  31575. this.renderList.reset();
  31576. };
  31577. BoundingBoxRenderer.prototype.render = function () {
  31578. if (this.renderList.length === 0) {
  31579. return;
  31580. }
  31581. this._prepareRessources();
  31582. if (!this._colorShader.isReady()) {
  31583. return;
  31584. }
  31585. var engine = this._scene.getEngine();
  31586. engine.setDepthWrite(false);
  31587. this._colorShader._preBind();
  31588. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31589. var boundingBox = this.renderList.data[boundingBoxIndex];
  31590. var min = boundingBox.minimum;
  31591. var max = boundingBox.maximum;
  31592. var diff = max.subtract(min);
  31593. var median = min.add(diff.scale(0.5));
  31594. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31595. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31596. .multiply(boundingBox.getWorldMatrix());
  31597. // VBOs
  31598. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31599. if (this.showBackLines) {
  31600. // Back
  31601. engine.setDepthFunctionToGreaterOrEqual();
  31602. this._scene.resetCachedMaterial();
  31603. this._colorShader.setColor4("color", this.backColor.toColor4());
  31604. this._colorShader.bind(worldMatrix);
  31605. // Draw order
  31606. engine.draw(false, 0, 24);
  31607. }
  31608. // Front
  31609. engine.setDepthFunctionToLess();
  31610. this._scene.resetCachedMaterial();
  31611. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31612. this._colorShader.bind(worldMatrix);
  31613. // Draw order
  31614. engine.draw(false, 0, 24);
  31615. }
  31616. this._colorShader.unbind();
  31617. engine.setDepthFunctionToLessOrEqual();
  31618. engine.setDepthWrite(true);
  31619. };
  31620. BoundingBoxRenderer.prototype.dispose = function () {
  31621. if (!this._colorShader) {
  31622. return;
  31623. }
  31624. this._colorShader.dispose();
  31625. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31626. if (buffer) {
  31627. buffer.dispose();
  31628. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31629. }
  31630. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31631. };
  31632. return BoundingBoxRenderer;
  31633. })();
  31634. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31635. })(BABYLON || (BABYLON = {}));
  31636. var BABYLON;
  31637. (function (BABYLON) {
  31638. var Condition = (function () {
  31639. function Condition(actionManager) {
  31640. this._actionManager = actionManager;
  31641. }
  31642. Condition.prototype.isValid = function () {
  31643. return true;
  31644. };
  31645. Condition.prototype._getProperty = function (propertyPath) {
  31646. return this._actionManager._getProperty(propertyPath);
  31647. };
  31648. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31649. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31650. };
  31651. Condition.prototype.serialize = function () {
  31652. };
  31653. Condition.prototype._serialize = function (serializedCondition) {
  31654. return {
  31655. type: 2,
  31656. children: [],
  31657. name: serializedCondition.name,
  31658. properties: serializedCondition.properties
  31659. };
  31660. };
  31661. return Condition;
  31662. })();
  31663. BABYLON.Condition = Condition;
  31664. var ValueCondition = (function (_super) {
  31665. __extends(ValueCondition, _super);
  31666. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31667. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31668. _super.call(this, actionManager);
  31669. this.propertyPath = propertyPath;
  31670. this.value = value;
  31671. this.operator = operator;
  31672. this._target = target;
  31673. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31674. this._property = this._getProperty(this.propertyPath);
  31675. }
  31676. Object.defineProperty(ValueCondition, "IsEqual", {
  31677. get: function () {
  31678. return ValueCondition._IsEqual;
  31679. },
  31680. enumerable: true,
  31681. configurable: true
  31682. });
  31683. Object.defineProperty(ValueCondition, "IsDifferent", {
  31684. get: function () {
  31685. return ValueCondition._IsDifferent;
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. Object.defineProperty(ValueCondition, "IsGreater", {
  31691. get: function () {
  31692. return ValueCondition._IsGreater;
  31693. },
  31694. enumerable: true,
  31695. configurable: true
  31696. });
  31697. Object.defineProperty(ValueCondition, "IsLesser", {
  31698. get: function () {
  31699. return ValueCondition._IsLesser;
  31700. },
  31701. enumerable: true,
  31702. configurable: true
  31703. });
  31704. // Methods
  31705. ValueCondition.prototype.isValid = function () {
  31706. switch (this.operator) {
  31707. case ValueCondition.IsGreater:
  31708. return this._effectiveTarget[this._property] > this.value;
  31709. case ValueCondition.IsLesser:
  31710. return this._effectiveTarget[this._property] < this.value;
  31711. case ValueCondition.IsEqual:
  31712. case ValueCondition.IsDifferent:
  31713. var check;
  31714. if (this.value.equals) {
  31715. check = this.value.equals(this._effectiveTarget[this._property]);
  31716. }
  31717. else {
  31718. check = this.value === this._effectiveTarget[this._property];
  31719. }
  31720. return this.operator === ValueCondition.IsEqual ? check : !check;
  31721. }
  31722. return false;
  31723. };
  31724. ValueCondition.prototype.serialize = function () {
  31725. return this._serialize({
  31726. name: "ValueCondition",
  31727. properties: [
  31728. BABYLON.Action._GetTargetProperty(this._target),
  31729. { name: "propertyPath", value: this.propertyPath },
  31730. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31731. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31732. ]
  31733. });
  31734. };
  31735. ValueCondition.GetOperatorName = function (operator) {
  31736. switch (operator) {
  31737. case ValueCondition._IsEqual: return "IsEqual";
  31738. case ValueCondition._IsDifferent: return "IsDifferent";
  31739. case ValueCondition._IsGreater: return "IsGreater";
  31740. case ValueCondition._IsLesser: return "IsLesser";
  31741. default: return "";
  31742. }
  31743. };
  31744. // Statics
  31745. ValueCondition._IsEqual = 0;
  31746. ValueCondition._IsDifferent = 1;
  31747. ValueCondition._IsGreater = 2;
  31748. ValueCondition._IsLesser = 3;
  31749. return ValueCondition;
  31750. })(Condition);
  31751. BABYLON.ValueCondition = ValueCondition;
  31752. var PredicateCondition = (function (_super) {
  31753. __extends(PredicateCondition, _super);
  31754. function PredicateCondition(actionManager, predicate) {
  31755. _super.call(this, actionManager);
  31756. this.predicate = predicate;
  31757. }
  31758. PredicateCondition.prototype.isValid = function () {
  31759. return this.predicate();
  31760. };
  31761. return PredicateCondition;
  31762. })(Condition);
  31763. BABYLON.PredicateCondition = PredicateCondition;
  31764. var StateCondition = (function (_super) {
  31765. __extends(StateCondition, _super);
  31766. function StateCondition(actionManager, target, value) {
  31767. _super.call(this, actionManager);
  31768. this.value = value;
  31769. this._target = target;
  31770. }
  31771. // Methods
  31772. StateCondition.prototype.isValid = function () {
  31773. return this._target.state === this.value;
  31774. };
  31775. StateCondition.prototype.serialize = function () {
  31776. return this._serialize({
  31777. name: "StateCondition",
  31778. properties: [
  31779. BABYLON.Action._GetTargetProperty(this._target),
  31780. { name: "value", value: this.value }
  31781. ]
  31782. });
  31783. };
  31784. return StateCondition;
  31785. })(Condition);
  31786. BABYLON.StateCondition = StateCondition;
  31787. })(BABYLON || (BABYLON = {}));
  31788. var BABYLON;
  31789. (function (BABYLON) {
  31790. var Action = (function () {
  31791. function Action(triggerOptions, condition) {
  31792. this.triggerOptions = triggerOptions;
  31793. if (triggerOptions.parameter) {
  31794. this.trigger = triggerOptions.trigger;
  31795. this._triggerParameter = triggerOptions.parameter;
  31796. }
  31797. else {
  31798. this.trigger = triggerOptions;
  31799. }
  31800. this._nextActiveAction = this;
  31801. this._condition = condition;
  31802. }
  31803. // Methods
  31804. Action.prototype._prepare = function () {
  31805. };
  31806. Action.prototype.getTriggerParameter = function () {
  31807. return this._triggerParameter;
  31808. };
  31809. Action.prototype._executeCurrent = function (evt) {
  31810. if (this._nextActiveAction._condition) {
  31811. var condition = this._nextActiveAction._condition;
  31812. var currentRenderId = this._actionManager.getScene().getRenderId();
  31813. // We cache the current evaluation for the current frame
  31814. if (condition._evaluationId === currentRenderId) {
  31815. if (!condition._currentResult) {
  31816. return;
  31817. }
  31818. }
  31819. else {
  31820. condition._evaluationId = currentRenderId;
  31821. if (!condition.isValid()) {
  31822. condition._currentResult = false;
  31823. return;
  31824. }
  31825. condition._currentResult = true;
  31826. }
  31827. }
  31828. this._nextActiveAction.execute(evt);
  31829. this.skipToNextActiveAction();
  31830. };
  31831. Action.prototype.execute = function (evt) {
  31832. };
  31833. Action.prototype.skipToNextActiveAction = function () {
  31834. if (this._nextActiveAction._child) {
  31835. if (!this._nextActiveAction._child._actionManager) {
  31836. this._nextActiveAction._child._actionManager = this._actionManager;
  31837. }
  31838. this._nextActiveAction = this._nextActiveAction._child;
  31839. }
  31840. else {
  31841. this._nextActiveAction = this;
  31842. }
  31843. };
  31844. Action.prototype.then = function (action) {
  31845. this._child = action;
  31846. action._actionManager = this._actionManager;
  31847. action._prepare();
  31848. return action;
  31849. };
  31850. Action.prototype._getProperty = function (propertyPath) {
  31851. return this._actionManager._getProperty(propertyPath);
  31852. };
  31853. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31854. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31855. };
  31856. Action.prototype.serialize = function (parent) {
  31857. };
  31858. // Called by BABYLON.Action objects in serialize(...). Internal use
  31859. Action.prototype._serialize = function (serializedAction, parent) {
  31860. var serializationObject = {
  31861. type: 1,
  31862. children: [],
  31863. name: serializedAction.name,
  31864. properties: serializedAction.properties || []
  31865. };
  31866. // Serialize child
  31867. if (this._child) {
  31868. this._child.serialize(serializationObject);
  31869. }
  31870. // Check if "this" has a condition
  31871. if (this._condition) {
  31872. var serializedCondition = this._condition.serialize();
  31873. serializedCondition.children.push(serializationObject);
  31874. if (parent) {
  31875. parent.children.push(serializedCondition);
  31876. }
  31877. return serializedCondition;
  31878. }
  31879. if (parent) {
  31880. parent.children.push(serializationObject);
  31881. }
  31882. return serializationObject;
  31883. };
  31884. Action._SerializeValueAsString = function (value) {
  31885. if (typeof value === "number") {
  31886. return value.toString();
  31887. }
  31888. if (typeof value === "boolean") {
  31889. return value ? "true" : "false";
  31890. }
  31891. if (value instanceof BABYLON.Vector2) {
  31892. return value.x + ", " + value.y;
  31893. }
  31894. if (value instanceof BABYLON.Vector3) {
  31895. return value.x + ", " + value.y + ", " + value.z;
  31896. }
  31897. if (value instanceof BABYLON.Color3) {
  31898. return value.r + ", " + value.g + ", " + value.b;
  31899. }
  31900. if (value instanceof BABYLON.Color4) {
  31901. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31902. }
  31903. return value; // string
  31904. };
  31905. Action._GetTargetProperty = function (target) {
  31906. return {
  31907. name: "target",
  31908. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31909. : target instanceof BABYLON.Light ? "LightProperties"
  31910. : target instanceof BABYLON.Camera ? "CameraProperties"
  31911. : "SceneProperties",
  31912. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31913. };
  31914. };
  31915. return Action;
  31916. })();
  31917. BABYLON.Action = Action;
  31918. })(BABYLON || (BABYLON = {}));
  31919. var BABYLON;
  31920. (function (BABYLON) {
  31921. /**
  31922. * ActionEvent is the event beint sent when an action is triggered.
  31923. */
  31924. var ActionEvent = (function () {
  31925. /**
  31926. * @constructor
  31927. * @param source The mesh or sprite that triggered the action.
  31928. * @param pointerX The X mouse cursor position at the time of the event
  31929. * @param pointerY The Y mouse cursor position at the time of the event
  31930. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31931. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31932. */
  31933. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31934. this.source = source;
  31935. this.pointerX = pointerX;
  31936. this.pointerY = pointerY;
  31937. this.meshUnderPointer = meshUnderPointer;
  31938. this.sourceEvent = sourceEvent;
  31939. this.additionalData = additionalData;
  31940. }
  31941. /**
  31942. * Helper function to auto-create an ActionEvent from a source mesh.
  31943. * @param source The source mesh that triggered the event
  31944. * @param evt {Event} The original (browser) event
  31945. */
  31946. ActionEvent.CreateNew = function (source, evt, additionalData) {
  31947. var scene = source.getScene();
  31948. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31949. };
  31950. /**
  31951. * Helper function to auto-create an ActionEvent from a source mesh.
  31952. * @param source The source sprite that triggered the event
  31953. * @param scene Scene associated with the sprite
  31954. * @param evt {Event} The original (browser) event
  31955. */
  31956. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  31957. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31958. };
  31959. /**
  31960. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  31961. * @param scene the scene where the event occurred
  31962. * @param evt {Event} The original (browser) event
  31963. */
  31964. ActionEvent.CreateNewFromScene = function (scene, evt) {
  31965. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  31966. };
  31967. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  31968. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  31969. };
  31970. return ActionEvent;
  31971. })();
  31972. BABYLON.ActionEvent = ActionEvent;
  31973. /**
  31974. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  31975. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  31976. */
  31977. var ActionManager = (function () {
  31978. function ActionManager(scene) {
  31979. // Members
  31980. this.actions = new Array();
  31981. this._scene = scene;
  31982. scene._actionManagers.push(this);
  31983. }
  31984. Object.defineProperty(ActionManager, "NothingTrigger", {
  31985. get: function () {
  31986. return ActionManager._NothingTrigger;
  31987. },
  31988. enumerable: true,
  31989. configurable: true
  31990. });
  31991. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31992. get: function () {
  31993. return ActionManager._OnPickTrigger;
  31994. },
  31995. enumerable: true,
  31996. configurable: true
  31997. });
  31998. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31999. get: function () {
  32000. return ActionManager._OnLeftPickTrigger;
  32001. },
  32002. enumerable: true,
  32003. configurable: true
  32004. });
  32005. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32006. get: function () {
  32007. return ActionManager._OnRightPickTrigger;
  32008. },
  32009. enumerable: true,
  32010. configurable: true
  32011. });
  32012. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32013. get: function () {
  32014. return ActionManager._OnCenterPickTrigger;
  32015. },
  32016. enumerable: true,
  32017. configurable: true
  32018. });
  32019. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32020. get: function () {
  32021. return ActionManager._OnPickDownTrigger;
  32022. },
  32023. enumerable: true,
  32024. configurable: true
  32025. });
  32026. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32027. get: function () {
  32028. return ActionManager._OnPickUpTrigger;
  32029. },
  32030. enumerable: true,
  32031. configurable: true
  32032. });
  32033. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32034. /// This trigger will only be raised if you also declared a OnPickDown
  32035. get: function () {
  32036. return ActionManager._OnPickOutTrigger;
  32037. },
  32038. enumerable: true,
  32039. configurable: true
  32040. });
  32041. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32042. get: function () {
  32043. return ActionManager._OnLongPressTrigger;
  32044. },
  32045. enumerable: true,
  32046. configurable: true
  32047. });
  32048. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32049. get: function () {
  32050. return ActionManager._OnPointerOverTrigger;
  32051. },
  32052. enumerable: true,
  32053. configurable: true
  32054. });
  32055. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32056. get: function () {
  32057. return ActionManager._OnPointerOutTrigger;
  32058. },
  32059. enumerable: true,
  32060. configurable: true
  32061. });
  32062. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32063. get: function () {
  32064. return ActionManager._OnEveryFrameTrigger;
  32065. },
  32066. enumerable: true,
  32067. configurable: true
  32068. });
  32069. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32070. get: function () {
  32071. return ActionManager._OnIntersectionEnterTrigger;
  32072. },
  32073. enumerable: true,
  32074. configurable: true
  32075. });
  32076. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32077. get: function () {
  32078. return ActionManager._OnIntersectionExitTrigger;
  32079. },
  32080. enumerable: true,
  32081. configurable: true
  32082. });
  32083. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32084. get: function () {
  32085. return ActionManager._OnKeyDownTrigger;
  32086. },
  32087. enumerable: true,
  32088. configurable: true
  32089. });
  32090. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32091. get: function () {
  32092. return ActionManager._OnKeyUpTrigger;
  32093. },
  32094. enumerable: true,
  32095. configurable: true
  32096. });
  32097. // Methods
  32098. ActionManager.prototype.dispose = function () {
  32099. var index = this._scene._actionManagers.indexOf(this);
  32100. if (index > -1) {
  32101. this._scene._actionManagers.splice(index, 1);
  32102. }
  32103. };
  32104. ActionManager.prototype.getScene = function () {
  32105. return this._scene;
  32106. };
  32107. /**
  32108. * Does this action manager handles actions of any of the given triggers
  32109. * @param {number[]} triggers - the triggers to be tested
  32110. * @return {boolean} whether one (or more) of the triggers is handeled
  32111. */
  32112. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32113. for (var index = 0; index < this.actions.length; index++) {
  32114. var action = this.actions[index];
  32115. if (triggers.indexOf(action.trigger) > -1) {
  32116. return true;
  32117. }
  32118. }
  32119. return false;
  32120. };
  32121. /**
  32122. * Does this action manager handles actions of a given trigger
  32123. * @param {number} trigger - the trigger to be tested
  32124. * @return {boolean} whether the trigger is handeled
  32125. */
  32126. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32127. for (var index = 0; index < this.actions.length; index++) {
  32128. var action = this.actions[index];
  32129. if (action.trigger === trigger) {
  32130. return true;
  32131. }
  32132. }
  32133. return false;
  32134. };
  32135. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32136. /**
  32137. * Does this action manager has pointer triggers
  32138. * @return {boolean} whether or not it has pointer triggers
  32139. */
  32140. get: function () {
  32141. for (var index = 0; index < this.actions.length; index++) {
  32142. var action = this.actions[index];
  32143. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32144. return true;
  32145. }
  32146. }
  32147. return false;
  32148. },
  32149. enumerable: true,
  32150. configurable: true
  32151. });
  32152. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32153. /**
  32154. * Does this action manager has pick triggers
  32155. * @return {boolean} whether or not it has pick triggers
  32156. */
  32157. get: function () {
  32158. for (var index = 0; index < this.actions.length; index++) {
  32159. var action = this.actions[index];
  32160. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32161. return true;
  32162. }
  32163. }
  32164. return false;
  32165. },
  32166. enumerable: true,
  32167. configurable: true
  32168. });
  32169. /**
  32170. * Registers an action to this action manager
  32171. * @param {BABYLON.Action} action - the action to be registered
  32172. * @return {BABYLON.Action} the action amended (prepared) after registration
  32173. */
  32174. ActionManager.prototype.registerAction = function (action) {
  32175. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32176. if (this.getScene().actionManager !== this) {
  32177. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32178. return null;
  32179. }
  32180. }
  32181. this.actions.push(action);
  32182. action._actionManager = this;
  32183. action._prepare();
  32184. return action;
  32185. };
  32186. /**
  32187. * Process a specific trigger
  32188. * @param {number} trigger - the trigger to process
  32189. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32190. */
  32191. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32192. for (var index = 0; index < this.actions.length; index++) {
  32193. var action = this.actions[index];
  32194. if (action.trigger === trigger) {
  32195. if (trigger === ActionManager.OnKeyUpTrigger
  32196. || trigger === ActionManager.OnKeyDownTrigger) {
  32197. var parameter = action.getTriggerParameter();
  32198. if (parameter) {
  32199. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32200. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32201. if (actualkey !== parameter.toLowerCase()) {
  32202. continue;
  32203. }
  32204. }
  32205. }
  32206. action._executeCurrent(evt);
  32207. }
  32208. }
  32209. };
  32210. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32211. var properties = propertyPath.split(".");
  32212. for (var index = 0; index < properties.length - 1; index++) {
  32213. target = target[properties[index]];
  32214. }
  32215. return target;
  32216. };
  32217. ActionManager.prototype._getProperty = function (propertyPath) {
  32218. var properties = propertyPath.split(".");
  32219. return properties[properties.length - 1];
  32220. };
  32221. ActionManager.prototype.serialize = function (name) {
  32222. var root = {
  32223. children: [],
  32224. name: name,
  32225. type: 3,
  32226. properties: [] // Empty for root but required
  32227. };
  32228. for (var i = 0; i < this.actions.length; i++) {
  32229. var triggerObject = {
  32230. type: 0,
  32231. children: [],
  32232. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32233. properties: []
  32234. };
  32235. var triggerOptions = this.actions[i].triggerOptions;
  32236. if (triggerOptions && typeof triggerOptions !== "number") {
  32237. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32238. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32239. }
  32240. else {
  32241. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32242. }
  32243. }
  32244. // Serialize child action, recursively
  32245. this.actions[i].serialize(triggerObject);
  32246. // Add serialized trigger
  32247. root.children.push(triggerObject);
  32248. }
  32249. return root;
  32250. };
  32251. ActionManager.Parse = function (parsedActions, object, scene) {
  32252. var actionManager = new BABYLON.ActionManager(scene);
  32253. if (object === null)
  32254. scene.actionManager = actionManager;
  32255. else
  32256. object.actionManager = actionManager;
  32257. // instanciate a new object
  32258. var instanciate = function (name, params) {
  32259. var newInstance = Object.create(BABYLON[name].prototype);
  32260. newInstance.constructor.apply(newInstance, params);
  32261. return newInstance;
  32262. };
  32263. var parseParameter = function (name, value, target, propertyPath) {
  32264. if (propertyPath === null) {
  32265. // String, boolean or float
  32266. var floatValue = parseFloat(value);
  32267. if (value === "true" || value === "false")
  32268. return value === "true";
  32269. else
  32270. return isNaN(floatValue) ? value : floatValue;
  32271. }
  32272. var effectiveTarget = propertyPath.split(".");
  32273. var values = value.split(",");
  32274. // Get effective Target
  32275. for (var i = 0; i < effectiveTarget.length; i++) {
  32276. target = target[effectiveTarget[i]];
  32277. }
  32278. // Return appropriate value with its type
  32279. if (typeof (target) === "boolean")
  32280. return values[0] === "true";
  32281. if (typeof (target) === "string")
  32282. return values[0];
  32283. // Parameters with multiple values such as Vector3 etc.
  32284. var split = new Array();
  32285. for (var i = 0; i < values.length; i++)
  32286. split.push(parseFloat(values[i]));
  32287. if (target instanceof BABYLON.Vector3)
  32288. return BABYLON.Vector3.FromArray(split);
  32289. if (target instanceof BABYLON.Vector4)
  32290. return BABYLON.Vector4.FromArray(split);
  32291. if (target instanceof BABYLON.Color3)
  32292. return BABYLON.Color3.FromArray(split);
  32293. if (target instanceof BABYLON.Color4)
  32294. return BABYLON.Color4.FromArray(split);
  32295. return parseFloat(values[0]);
  32296. };
  32297. // traverse graph per trigger
  32298. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32299. if (combineArray === void 0) { combineArray = null; }
  32300. if (parsedAction.detached)
  32301. return;
  32302. var parameters = new Array();
  32303. var target = null;
  32304. var propertyPath = null;
  32305. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32306. // Parameters
  32307. if (parsedAction.type === 2)
  32308. parameters.push(actionManager);
  32309. else
  32310. parameters.push(trigger);
  32311. if (combine) {
  32312. var actions = new Array();
  32313. for (var j = 0; j < parsedAction.combine.length; j++) {
  32314. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32315. }
  32316. parameters.push(actions);
  32317. }
  32318. else {
  32319. for (var i = 0; i < parsedAction.properties.length; i++) {
  32320. var value = parsedAction.properties[i].value;
  32321. var name = parsedAction.properties[i].name;
  32322. var targetType = parsedAction.properties[i].targetType;
  32323. if (name === "target")
  32324. if (targetType !== null && targetType === "SceneProperties")
  32325. value = target = scene;
  32326. else
  32327. value = target = scene.getNodeByName(value);
  32328. else if (name === "parent")
  32329. value = scene.getNodeByName(value);
  32330. else if (name === "sound")
  32331. value = scene.getSoundByName(value);
  32332. else if (name !== "propertyPath") {
  32333. if (parsedAction.type === 2 && name === "operator")
  32334. value = BABYLON.ValueCondition[value];
  32335. else
  32336. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32337. }
  32338. else {
  32339. propertyPath = value;
  32340. }
  32341. parameters.push(value);
  32342. }
  32343. }
  32344. if (combineArray === null) {
  32345. parameters.push(condition);
  32346. }
  32347. else {
  32348. parameters.push(null);
  32349. }
  32350. // If interpolate value action
  32351. if (parsedAction.name === "InterpolateValueAction") {
  32352. var param = parameters[parameters.length - 2];
  32353. parameters[parameters.length - 1] = param;
  32354. parameters[parameters.length - 2] = condition;
  32355. }
  32356. // Action or condition(s) and not CombineAction
  32357. var newAction = instanciate(parsedAction.name, parameters);
  32358. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32359. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32360. if (action)
  32361. action.then(nothing);
  32362. else
  32363. actionManager.registerAction(nothing);
  32364. action = nothing;
  32365. }
  32366. if (combineArray === null) {
  32367. if (newAction instanceof BABYLON.Condition) {
  32368. condition = newAction;
  32369. newAction = action;
  32370. }
  32371. else {
  32372. condition = null;
  32373. if (action)
  32374. action.then(newAction);
  32375. else
  32376. actionManager.registerAction(newAction);
  32377. }
  32378. }
  32379. else {
  32380. combineArray.push(newAction);
  32381. }
  32382. for (var i = 0; i < parsedAction.children.length; i++)
  32383. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32384. };
  32385. // triggers
  32386. for (var i = 0; i < parsedActions.children.length; i++) {
  32387. var triggerParams;
  32388. var trigger = parsedActions.children[i];
  32389. if (trigger.properties.length > 0) {
  32390. var param = trigger.properties[0].value;
  32391. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32392. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32393. }
  32394. else
  32395. triggerParams = BABYLON.ActionManager[trigger.name];
  32396. for (var j = 0; j < trigger.children.length; j++) {
  32397. if (!trigger.detached)
  32398. traverse(trigger.children[j], triggerParams, null, null);
  32399. }
  32400. }
  32401. };
  32402. ActionManager.GetTriggerName = function (trigger) {
  32403. switch (trigger) {
  32404. case 0: return "NothingTrigger";
  32405. case 1: return "OnPickTrigger";
  32406. case 2: return "OnLeftPickTrigger";
  32407. case 3: return "OnRightPickTrigger";
  32408. case 4: return "OnCenterPickTrigger";
  32409. case 5: return "OnPickDownTrigger";
  32410. case 6: return "OnPickUpTrigger";
  32411. case 7: return "OnLongPressTrigger";
  32412. case 8: return "OnPointerOverTrigger";
  32413. case 9: return "OnPointerOutTrigger";
  32414. case 10: return "OnEveryFrameTrigger";
  32415. case 11: return "OnIntersectionEnterTrigger";
  32416. case 12: return "OnIntersectionExitTrigger";
  32417. case 13: return "OnKeyDownTrigger";
  32418. case 14: return "OnKeyUpTrigger";
  32419. case 15: return "OnPickOutTrigger";
  32420. default: return "";
  32421. }
  32422. };
  32423. // Statics
  32424. ActionManager._NothingTrigger = 0;
  32425. ActionManager._OnPickTrigger = 1;
  32426. ActionManager._OnLeftPickTrigger = 2;
  32427. ActionManager._OnRightPickTrigger = 3;
  32428. ActionManager._OnCenterPickTrigger = 4;
  32429. ActionManager._OnPickDownTrigger = 5;
  32430. ActionManager._OnPickUpTrigger = 6;
  32431. ActionManager._OnLongPressTrigger = 7;
  32432. ActionManager._OnPointerOverTrigger = 8;
  32433. ActionManager._OnPointerOutTrigger = 9;
  32434. ActionManager._OnEveryFrameTrigger = 10;
  32435. ActionManager._OnIntersectionEnterTrigger = 11;
  32436. ActionManager._OnIntersectionExitTrigger = 12;
  32437. ActionManager._OnKeyDownTrigger = 13;
  32438. ActionManager._OnKeyUpTrigger = 14;
  32439. ActionManager._OnPickOutTrigger = 15;
  32440. ActionManager.DragMovementThreshold = 10; // in pixels
  32441. ActionManager.LongPressDelay = 500; // in milliseconds
  32442. return ActionManager;
  32443. })();
  32444. BABYLON.ActionManager = ActionManager;
  32445. })(BABYLON || (BABYLON = {}));
  32446. var BABYLON;
  32447. (function (BABYLON) {
  32448. var InterpolateValueAction = (function (_super) {
  32449. __extends(InterpolateValueAction, _super);
  32450. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32451. if (duration === void 0) { duration = 1000; }
  32452. _super.call(this, triggerOptions, condition);
  32453. this.propertyPath = propertyPath;
  32454. this.value = value;
  32455. this.duration = duration;
  32456. this.stopOtherAnimations = stopOtherAnimations;
  32457. this.onInterpolationDone = onInterpolationDone;
  32458. this._target = this._effectiveTarget = target;
  32459. }
  32460. InterpolateValueAction.prototype._prepare = function () {
  32461. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32462. this._property = this._getProperty(this.propertyPath);
  32463. };
  32464. InterpolateValueAction.prototype.execute = function () {
  32465. var scene = this._actionManager.getScene();
  32466. var keys = [
  32467. {
  32468. frame: 0,
  32469. value: this._effectiveTarget[this._property]
  32470. }, {
  32471. frame: 100,
  32472. value: this.value
  32473. }
  32474. ];
  32475. var dataType;
  32476. if (typeof this.value === "number") {
  32477. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32478. }
  32479. else if (this.value instanceof BABYLON.Color3) {
  32480. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32481. }
  32482. else if (this.value instanceof BABYLON.Vector3) {
  32483. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32484. }
  32485. else if (this.value instanceof BABYLON.Matrix) {
  32486. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32487. }
  32488. else if (this.value instanceof BABYLON.Quaternion) {
  32489. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32490. }
  32491. else {
  32492. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32493. return;
  32494. }
  32495. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32496. animation.setKeys(keys);
  32497. if (this.stopOtherAnimations) {
  32498. scene.stopAnimation(this._effectiveTarget);
  32499. }
  32500. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32501. };
  32502. InterpolateValueAction.prototype.serialize = function (parent) {
  32503. return _super.prototype._serialize.call(this, {
  32504. name: "InterpolateValueAction",
  32505. properties: [
  32506. BABYLON.Action._GetTargetProperty(this._target),
  32507. { name: "propertyPath", value: this.propertyPath },
  32508. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32509. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32510. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32511. ]
  32512. }, parent);
  32513. };
  32514. return InterpolateValueAction;
  32515. })(BABYLON.Action);
  32516. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32517. })(BABYLON || (BABYLON = {}));
  32518. var BABYLON;
  32519. (function (BABYLON) {
  32520. var SwitchBooleanAction = (function (_super) {
  32521. __extends(SwitchBooleanAction, _super);
  32522. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32523. _super.call(this, triggerOptions, condition);
  32524. this.propertyPath = propertyPath;
  32525. this._target = this._effectiveTarget = target;
  32526. }
  32527. SwitchBooleanAction.prototype._prepare = function () {
  32528. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32529. this._property = this._getProperty(this.propertyPath);
  32530. };
  32531. SwitchBooleanAction.prototype.execute = function () {
  32532. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32533. };
  32534. SwitchBooleanAction.prototype.serialize = function (parent) {
  32535. return _super.prototype._serialize.call(this, {
  32536. name: "SwitchBooleanAction",
  32537. properties: [
  32538. BABYLON.Action._GetTargetProperty(this._target),
  32539. { name: "propertyPath", value: this.propertyPath }
  32540. ]
  32541. }, parent);
  32542. };
  32543. return SwitchBooleanAction;
  32544. })(BABYLON.Action);
  32545. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32546. var SetStateAction = (function (_super) {
  32547. __extends(SetStateAction, _super);
  32548. function SetStateAction(triggerOptions, target, value, condition) {
  32549. _super.call(this, triggerOptions, condition);
  32550. this.value = value;
  32551. this._target = target;
  32552. }
  32553. SetStateAction.prototype.execute = function () {
  32554. this._target.state = this.value;
  32555. };
  32556. SetStateAction.prototype.serialize = function (parent) {
  32557. return _super.prototype._serialize.call(this, {
  32558. name: "SetStateAction",
  32559. properties: [
  32560. BABYLON.Action._GetTargetProperty(this._target),
  32561. { name: "value", value: this.value }
  32562. ]
  32563. }, parent);
  32564. };
  32565. return SetStateAction;
  32566. })(BABYLON.Action);
  32567. BABYLON.SetStateAction = SetStateAction;
  32568. var SetValueAction = (function (_super) {
  32569. __extends(SetValueAction, _super);
  32570. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32571. _super.call(this, triggerOptions, condition);
  32572. this.propertyPath = propertyPath;
  32573. this.value = value;
  32574. this._target = this._effectiveTarget = target;
  32575. }
  32576. SetValueAction.prototype._prepare = function () {
  32577. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32578. this._property = this._getProperty(this.propertyPath);
  32579. };
  32580. SetValueAction.prototype.execute = function () {
  32581. this._effectiveTarget[this._property] = this.value;
  32582. if (this._target.markAsDirty) {
  32583. this._target.markAsDirty(this._property);
  32584. }
  32585. };
  32586. SetValueAction.prototype.serialize = function (parent) {
  32587. return _super.prototype._serialize.call(this, {
  32588. name: "SetValueAction",
  32589. properties: [
  32590. BABYLON.Action._GetTargetProperty(this._target),
  32591. { name: "propertyPath", value: this.propertyPath },
  32592. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32593. ]
  32594. }, parent);
  32595. };
  32596. return SetValueAction;
  32597. })(BABYLON.Action);
  32598. BABYLON.SetValueAction = SetValueAction;
  32599. var IncrementValueAction = (function (_super) {
  32600. __extends(IncrementValueAction, _super);
  32601. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32602. _super.call(this, triggerOptions, condition);
  32603. this.propertyPath = propertyPath;
  32604. this.value = value;
  32605. this._target = this._effectiveTarget = target;
  32606. }
  32607. IncrementValueAction.prototype._prepare = function () {
  32608. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32609. this._property = this._getProperty(this.propertyPath);
  32610. if (typeof this._effectiveTarget[this._property] !== "number") {
  32611. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32612. }
  32613. };
  32614. IncrementValueAction.prototype.execute = function () {
  32615. this._effectiveTarget[this._property] += this.value;
  32616. if (this._target.markAsDirty) {
  32617. this._target.markAsDirty(this._property);
  32618. }
  32619. };
  32620. IncrementValueAction.prototype.serialize = function (parent) {
  32621. return _super.prototype._serialize.call(this, {
  32622. name: "IncrementValueAction",
  32623. properties: [
  32624. BABYLON.Action._GetTargetProperty(this._target),
  32625. { name: "propertyPath", value: this.propertyPath },
  32626. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32627. ]
  32628. }, parent);
  32629. };
  32630. return IncrementValueAction;
  32631. })(BABYLON.Action);
  32632. BABYLON.IncrementValueAction = IncrementValueAction;
  32633. var PlayAnimationAction = (function (_super) {
  32634. __extends(PlayAnimationAction, _super);
  32635. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32636. _super.call(this, triggerOptions, condition);
  32637. this.from = from;
  32638. this.to = to;
  32639. this.loop = loop;
  32640. this._target = target;
  32641. }
  32642. PlayAnimationAction.prototype._prepare = function () {
  32643. };
  32644. PlayAnimationAction.prototype.execute = function () {
  32645. var scene = this._actionManager.getScene();
  32646. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32647. };
  32648. PlayAnimationAction.prototype.serialize = function (parent) {
  32649. return _super.prototype._serialize.call(this, {
  32650. name: "PlayAnimationAction",
  32651. properties: [
  32652. BABYLON.Action._GetTargetProperty(this._target),
  32653. { name: "from", value: String(this.from) },
  32654. { name: "to", value: String(this.to) },
  32655. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32656. ]
  32657. }, parent);
  32658. };
  32659. return PlayAnimationAction;
  32660. })(BABYLON.Action);
  32661. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32662. var StopAnimationAction = (function (_super) {
  32663. __extends(StopAnimationAction, _super);
  32664. function StopAnimationAction(triggerOptions, target, condition) {
  32665. _super.call(this, triggerOptions, condition);
  32666. this._target = target;
  32667. }
  32668. StopAnimationAction.prototype._prepare = function () {
  32669. };
  32670. StopAnimationAction.prototype.execute = function () {
  32671. var scene = this._actionManager.getScene();
  32672. scene.stopAnimation(this._target);
  32673. };
  32674. StopAnimationAction.prototype.serialize = function (parent) {
  32675. return _super.prototype._serialize.call(this, {
  32676. name: "StopAnimationAction",
  32677. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32678. }, parent);
  32679. };
  32680. return StopAnimationAction;
  32681. })(BABYLON.Action);
  32682. BABYLON.StopAnimationAction = StopAnimationAction;
  32683. var DoNothingAction = (function (_super) {
  32684. __extends(DoNothingAction, _super);
  32685. function DoNothingAction(triggerOptions, condition) {
  32686. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32687. _super.call(this, triggerOptions, condition);
  32688. }
  32689. DoNothingAction.prototype.execute = function () {
  32690. };
  32691. DoNothingAction.prototype.serialize = function (parent) {
  32692. return _super.prototype._serialize.call(this, {
  32693. name: "DoNothingAction",
  32694. properties: []
  32695. }, parent);
  32696. };
  32697. return DoNothingAction;
  32698. })(BABYLON.Action);
  32699. BABYLON.DoNothingAction = DoNothingAction;
  32700. var CombineAction = (function (_super) {
  32701. __extends(CombineAction, _super);
  32702. function CombineAction(triggerOptions, children, condition) {
  32703. _super.call(this, triggerOptions, condition);
  32704. this.children = children;
  32705. }
  32706. CombineAction.prototype._prepare = function () {
  32707. for (var index = 0; index < this.children.length; index++) {
  32708. this.children[index]._actionManager = this._actionManager;
  32709. this.children[index]._prepare();
  32710. }
  32711. };
  32712. CombineAction.prototype.execute = function (evt) {
  32713. for (var index = 0; index < this.children.length; index++) {
  32714. this.children[index].execute(evt);
  32715. }
  32716. };
  32717. CombineAction.prototype.serialize = function (parent) {
  32718. var serializationObject = _super.prototype._serialize.call(this, {
  32719. name: "CombineAction",
  32720. properties: [],
  32721. combine: []
  32722. }, parent);
  32723. for (var i = 0; i < this.children.length; i++) {
  32724. serializationObject.combine.push(this.children[i].serialize(null));
  32725. }
  32726. return serializationObject;
  32727. };
  32728. return CombineAction;
  32729. })(BABYLON.Action);
  32730. BABYLON.CombineAction = CombineAction;
  32731. var ExecuteCodeAction = (function (_super) {
  32732. __extends(ExecuteCodeAction, _super);
  32733. function ExecuteCodeAction(triggerOptions, func, condition) {
  32734. _super.call(this, triggerOptions, condition);
  32735. this.func = func;
  32736. }
  32737. ExecuteCodeAction.prototype.execute = function (evt) {
  32738. this.func(evt);
  32739. };
  32740. return ExecuteCodeAction;
  32741. })(BABYLON.Action);
  32742. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32743. var SetParentAction = (function (_super) {
  32744. __extends(SetParentAction, _super);
  32745. function SetParentAction(triggerOptions, target, parent, condition) {
  32746. _super.call(this, triggerOptions, condition);
  32747. this._target = target;
  32748. this._parent = parent;
  32749. }
  32750. SetParentAction.prototype._prepare = function () {
  32751. };
  32752. SetParentAction.prototype.execute = function () {
  32753. if (this._target.parent === this._parent) {
  32754. return;
  32755. }
  32756. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32757. invertParentWorldMatrix.invert();
  32758. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32759. this._target.parent = this._parent;
  32760. };
  32761. SetParentAction.prototype.serialize = function (parent) {
  32762. return _super.prototype._serialize.call(this, {
  32763. name: "SetParentAction",
  32764. properties: [
  32765. BABYLON.Action._GetTargetProperty(this._target),
  32766. BABYLON.Action._GetTargetProperty(this._parent),
  32767. ]
  32768. }, parent);
  32769. };
  32770. return SetParentAction;
  32771. })(BABYLON.Action);
  32772. BABYLON.SetParentAction = SetParentAction;
  32773. var PlaySoundAction = (function (_super) {
  32774. __extends(PlaySoundAction, _super);
  32775. function PlaySoundAction(triggerOptions, sound, condition) {
  32776. _super.call(this, triggerOptions, condition);
  32777. this._sound = sound;
  32778. }
  32779. PlaySoundAction.prototype._prepare = function () {
  32780. };
  32781. PlaySoundAction.prototype.execute = function () {
  32782. if (this._sound !== undefined)
  32783. this._sound.play();
  32784. };
  32785. PlaySoundAction.prototype.serialize = function (parent) {
  32786. return _super.prototype._serialize.call(this, {
  32787. name: "PlaySoundAction",
  32788. properties: [{ name: "sound", value: this._sound.name }]
  32789. }, parent);
  32790. };
  32791. return PlaySoundAction;
  32792. })(BABYLON.Action);
  32793. BABYLON.PlaySoundAction = PlaySoundAction;
  32794. var StopSoundAction = (function (_super) {
  32795. __extends(StopSoundAction, _super);
  32796. function StopSoundAction(triggerOptions, sound, condition) {
  32797. _super.call(this, triggerOptions, condition);
  32798. this._sound = sound;
  32799. }
  32800. StopSoundAction.prototype._prepare = function () {
  32801. };
  32802. StopSoundAction.prototype.execute = function () {
  32803. if (this._sound !== undefined)
  32804. this._sound.stop();
  32805. };
  32806. StopSoundAction.prototype.serialize = function (parent) {
  32807. return _super.prototype._serialize.call(this, {
  32808. name: "StopSoundAction",
  32809. properties: [{ name: "sound", value: this._sound.name }]
  32810. }, parent);
  32811. };
  32812. return StopSoundAction;
  32813. })(BABYLON.Action);
  32814. BABYLON.StopSoundAction = StopSoundAction;
  32815. })(BABYLON || (BABYLON = {}));
  32816. var BABYLON;
  32817. (function (BABYLON) {
  32818. var Geometry = (function () {
  32819. function Geometry(id, scene, vertexData, updatable, mesh) {
  32820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32821. this._totalVertices = 0;
  32822. this._isDisposed = false;
  32823. this.id = id;
  32824. this._engine = scene.getEngine();
  32825. this._meshes = [];
  32826. this._scene = scene;
  32827. //Init vertex buffer cache
  32828. this._vertexBuffers = {};
  32829. this._indices = [];
  32830. // vertexData
  32831. if (vertexData) {
  32832. this.setAllVerticesData(vertexData, updatable);
  32833. }
  32834. else {
  32835. this._totalVertices = 0;
  32836. this._indices = [];
  32837. }
  32838. // applyToMesh
  32839. if (mesh) {
  32840. if (mesh instanceof BABYLON.LinesMesh) {
  32841. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32842. this.updateExtend();
  32843. }
  32844. this.applyToMesh(mesh);
  32845. mesh.computeWorldMatrix(true);
  32846. }
  32847. }
  32848. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32849. /**
  32850. * 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
  32851. * @returns The Bias Vector
  32852. */
  32853. get: function () {
  32854. return this._boundingBias;
  32855. },
  32856. set: function (value) {
  32857. if (this._boundingBias && this._boundingBias.equals(value)) {
  32858. return;
  32859. }
  32860. this._boundingBias = value.clone();
  32861. this.updateBoundingInfo(true, null);
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. Object.defineProperty(Geometry.prototype, "extend", {
  32867. get: function () {
  32868. return this._extend;
  32869. },
  32870. enumerable: true,
  32871. configurable: true
  32872. });
  32873. Geometry.prototype.getScene = function () {
  32874. return this._scene;
  32875. };
  32876. Geometry.prototype.getEngine = function () {
  32877. return this._engine;
  32878. };
  32879. Geometry.prototype.isReady = function () {
  32880. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32881. };
  32882. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32883. vertexData.applyToGeometry(this, updatable);
  32884. this.notifyUpdate();
  32885. };
  32886. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32887. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32888. this.setVerticesBuffer(buffer);
  32889. };
  32890. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32891. var kind = buffer.getKind();
  32892. if (this._vertexBuffers[kind]) {
  32893. this._vertexBuffers[kind].dispose();
  32894. }
  32895. this._vertexBuffers[kind] = buffer;
  32896. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32897. var data = buffer.getData();
  32898. var stride = buffer.getStrideSize();
  32899. this._totalVertices = data.length / stride;
  32900. this.updateExtend(data, stride);
  32901. var meshes = this._meshes;
  32902. var numOfMeshes = meshes.length;
  32903. for (var index = 0; index < numOfMeshes; index++) {
  32904. var mesh = meshes[index];
  32905. mesh._resetPointsArrayCache();
  32906. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32907. mesh._createGlobalSubMesh();
  32908. mesh.computeWorldMatrix(true);
  32909. }
  32910. }
  32911. this.notifyUpdate(kind);
  32912. };
  32913. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32914. var vertexBuffer = this.getVertexBuffer(kind);
  32915. if (!vertexBuffer) {
  32916. return;
  32917. }
  32918. vertexBuffer.updateDirectly(data, offset);
  32919. this.notifyUpdate(kind);
  32920. };
  32921. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32922. var vertexBuffer = this.getVertexBuffer(kind);
  32923. if (!vertexBuffer) {
  32924. return;
  32925. }
  32926. vertexBuffer.update(data);
  32927. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32928. var stride = vertexBuffer.getStrideSize();
  32929. this._totalVertices = data.length / stride;
  32930. this.updateBoundingInfo(updateExtends, data);
  32931. }
  32932. this.notifyUpdate(kind);
  32933. };
  32934. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32935. if (updateExtends) {
  32936. this.updateExtend(data);
  32937. }
  32938. var meshes = this._meshes;
  32939. var numOfMeshes = meshes.length;
  32940. for (var index = 0; index < numOfMeshes; index++) {
  32941. var mesh = meshes[index];
  32942. mesh._resetPointsArrayCache();
  32943. if (updateExtends) {
  32944. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32945. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32946. var subMesh = mesh.subMeshes[subIndex];
  32947. subMesh.refreshBoundingInfo();
  32948. }
  32949. }
  32950. }
  32951. };
  32952. Geometry.prototype.getTotalVertices = function () {
  32953. if (!this.isReady()) {
  32954. return 0;
  32955. }
  32956. return this._totalVertices;
  32957. };
  32958. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  32959. var vertexBuffer = this.getVertexBuffer(kind);
  32960. if (!vertexBuffer) {
  32961. return null;
  32962. }
  32963. var orig = vertexBuffer.getData();
  32964. if (!copyWhenShared || this._meshes.length === 1) {
  32965. return orig;
  32966. }
  32967. else {
  32968. var len = orig.length;
  32969. var copy = [];
  32970. for (var i = 0; i < len; i++) {
  32971. copy.push(orig[i]);
  32972. }
  32973. return copy;
  32974. }
  32975. };
  32976. Geometry.prototype.getVertexBuffer = function (kind) {
  32977. if (!this.isReady()) {
  32978. return null;
  32979. }
  32980. return this._vertexBuffers[kind];
  32981. };
  32982. Geometry.prototype.getVertexBuffers = function () {
  32983. if (!this.isReady()) {
  32984. return null;
  32985. }
  32986. return this._vertexBuffers;
  32987. };
  32988. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32989. if (!this._vertexBuffers) {
  32990. if (this._delayInfo) {
  32991. return this._delayInfo.indexOf(kind) !== -1;
  32992. }
  32993. return false;
  32994. }
  32995. return this._vertexBuffers[kind] !== undefined;
  32996. };
  32997. Geometry.prototype.getVerticesDataKinds = function () {
  32998. var result = [];
  32999. var kind;
  33000. if (!this._vertexBuffers && this._delayInfo) {
  33001. for (kind in this._delayInfo) {
  33002. result.push(kind);
  33003. }
  33004. }
  33005. else {
  33006. for (kind in this._vertexBuffers) {
  33007. result.push(kind);
  33008. }
  33009. }
  33010. return result;
  33011. };
  33012. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33013. if (this._indexBuffer) {
  33014. this._engine._releaseBuffer(this._indexBuffer);
  33015. }
  33016. this._indices = indices;
  33017. if (this._meshes.length !== 0 && this._indices) {
  33018. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33019. }
  33020. if (totalVertices !== undefined) {
  33021. this._totalVertices = totalVertices;
  33022. }
  33023. var meshes = this._meshes;
  33024. var numOfMeshes = meshes.length;
  33025. for (var index = 0; index < numOfMeshes; index++) {
  33026. meshes[index]._createGlobalSubMesh();
  33027. }
  33028. this.notifyUpdate();
  33029. };
  33030. Geometry.prototype.getTotalIndices = function () {
  33031. if (!this.isReady()) {
  33032. return 0;
  33033. }
  33034. return this._indices.length;
  33035. };
  33036. Geometry.prototype.getIndices = function (copyWhenShared) {
  33037. if (!this.isReady()) {
  33038. return null;
  33039. }
  33040. var orig = this._indices;
  33041. if (!copyWhenShared || this._meshes.length === 1) {
  33042. return orig;
  33043. }
  33044. else {
  33045. var len = orig.length;
  33046. var copy = [];
  33047. for (var i = 0; i < len; i++) {
  33048. copy.push(orig[i]);
  33049. }
  33050. return copy;
  33051. }
  33052. };
  33053. Geometry.prototype.getIndexBuffer = function () {
  33054. if (!this.isReady()) {
  33055. return null;
  33056. }
  33057. return this._indexBuffer;
  33058. };
  33059. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33060. var meshes = this._meshes;
  33061. var index = meshes.indexOf(mesh);
  33062. if (index === -1) {
  33063. return;
  33064. }
  33065. for (var kind in this._vertexBuffers) {
  33066. this._vertexBuffers[kind].dispose();
  33067. }
  33068. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33069. this._indexBuffer = null;
  33070. }
  33071. meshes.splice(index, 1);
  33072. mesh._geometry = null;
  33073. if (meshes.length === 0 && shouldDispose) {
  33074. this.dispose();
  33075. }
  33076. };
  33077. Geometry.prototype.applyToMesh = function (mesh) {
  33078. if (mesh._geometry === this) {
  33079. return;
  33080. }
  33081. var previousGeometry = mesh._geometry;
  33082. if (previousGeometry) {
  33083. previousGeometry.releaseForMesh(mesh);
  33084. }
  33085. var meshes = this._meshes;
  33086. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33087. mesh._geometry = this;
  33088. this._scene.pushGeometry(this);
  33089. meshes.push(mesh);
  33090. if (this.isReady()) {
  33091. this._applyToMesh(mesh);
  33092. }
  33093. else {
  33094. mesh._boundingInfo = this._boundingInfo;
  33095. }
  33096. };
  33097. Geometry.prototype.updateExtend = function (data, stride) {
  33098. if (data === void 0) { data = null; }
  33099. if (!data) {
  33100. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33101. }
  33102. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33103. };
  33104. Geometry.prototype._applyToMesh = function (mesh) {
  33105. var numOfMeshes = this._meshes.length;
  33106. // vertexBuffers
  33107. for (var kind in this._vertexBuffers) {
  33108. if (numOfMeshes === 1) {
  33109. this._vertexBuffers[kind].create();
  33110. }
  33111. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33112. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33113. mesh._resetPointsArrayCache();
  33114. if (!this._extend) {
  33115. this.updateExtend(this._vertexBuffers[kind].getData());
  33116. }
  33117. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33118. mesh._createGlobalSubMesh();
  33119. //bounding info was just created again, world matrix should be applied again.
  33120. mesh._updateBoundingInfo();
  33121. }
  33122. }
  33123. // indexBuffer
  33124. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33125. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33126. }
  33127. if (this._indexBuffer) {
  33128. this._indexBuffer.references = numOfMeshes;
  33129. }
  33130. };
  33131. Geometry.prototype.notifyUpdate = function (kind) {
  33132. if (this.onGeometryUpdated) {
  33133. this.onGeometryUpdated(this, kind);
  33134. }
  33135. };
  33136. Geometry.prototype.load = function (scene, onLoaded) {
  33137. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33138. return;
  33139. }
  33140. if (this.isReady()) {
  33141. if (onLoaded) {
  33142. onLoaded();
  33143. }
  33144. return;
  33145. }
  33146. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33147. this._queueLoad(scene, onLoaded);
  33148. };
  33149. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33150. var _this = this;
  33151. scene._addPendingData(this);
  33152. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33153. _this._delayLoadingFunction(JSON.parse(data), _this);
  33154. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33155. _this._delayInfo = [];
  33156. scene._removePendingData(_this);
  33157. var meshes = _this._meshes;
  33158. var numOfMeshes = meshes.length;
  33159. for (var index = 0; index < numOfMeshes; index++) {
  33160. _this._applyToMesh(meshes[index]);
  33161. }
  33162. if (onLoaded) {
  33163. onLoaded();
  33164. }
  33165. }, function () { }, scene.database);
  33166. };
  33167. /**
  33168. * Invert the geometry to move from a right handed system to a left handed one.
  33169. */
  33170. Geometry.prototype.toLeftHanded = function () {
  33171. // Flip faces
  33172. var tIndices = this.getIndices(false);
  33173. if (tIndices != null && tIndices.length > 0) {
  33174. for (var i = 0; i < tIndices.length; i += 3) {
  33175. var tTemp = tIndices[i + 0];
  33176. tIndices[i + 0] = tIndices[i + 2];
  33177. tIndices[i + 2] = tTemp;
  33178. }
  33179. this.setIndices(tIndices);
  33180. }
  33181. // Negate position.z
  33182. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33183. if (tPositions != null && tPositions.length > 0) {
  33184. for (var i = 0; i < tPositions.length; i += 3) {
  33185. tPositions[i + 2] = -tPositions[i + 2];
  33186. }
  33187. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33188. }
  33189. // Negate normal.z
  33190. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33191. if (tNormals != null && tNormals.length > 0) {
  33192. for (var i = 0; i < tNormals.length; i += 3) {
  33193. tNormals[i + 2] = -tNormals[i + 2];
  33194. }
  33195. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33196. }
  33197. };
  33198. Geometry.prototype.isDisposed = function () {
  33199. return this._isDisposed;
  33200. };
  33201. Geometry.prototype.dispose = function () {
  33202. var meshes = this._meshes;
  33203. var numOfMeshes = meshes.length;
  33204. var index;
  33205. for (index = 0; index < numOfMeshes; index++) {
  33206. this.releaseForMesh(meshes[index]);
  33207. }
  33208. this._meshes = [];
  33209. for (var kind in this._vertexBuffers) {
  33210. this._vertexBuffers[kind].dispose();
  33211. }
  33212. this._vertexBuffers = {};
  33213. this._totalVertices = 0;
  33214. if (this._indexBuffer) {
  33215. this._engine._releaseBuffer(this._indexBuffer);
  33216. }
  33217. this._indexBuffer = null;
  33218. this._indices = [];
  33219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33220. this.delayLoadingFile = null;
  33221. this._delayLoadingFunction = null;
  33222. this._delayInfo = [];
  33223. this._boundingInfo = null;
  33224. this._scene.removeGeometry(this);
  33225. this._isDisposed = true;
  33226. };
  33227. Geometry.prototype.copy = function (id) {
  33228. var vertexData = new BABYLON.VertexData();
  33229. vertexData.indices = [];
  33230. var indices = this.getIndices();
  33231. for (var index = 0; index < indices.length; index++) {
  33232. vertexData.indices.push(indices[index]);
  33233. }
  33234. var updatable = false;
  33235. var stopChecking = false;
  33236. var kind;
  33237. for (kind in this._vertexBuffers) {
  33238. // using slice() to make a copy of the array and not just reference it
  33239. var data = this.getVerticesData(kind);
  33240. if (data instanceof Float32Array) {
  33241. vertexData.set(new Float32Array(data), kind);
  33242. }
  33243. else {
  33244. vertexData.set(data.slice(0), kind);
  33245. }
  33246. if (!stopChecking) {
  33247. updatable = this.getVertexBuffer(kind).isUpdatable();
  33248. stopChecking = !updatable;
  33249. }
  33250. }
  33251. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33252. geometry.delayLoadState = this.delayLoadState;
  33253. geometry.delayLoadingFile = this.delayLoadingFile;
  33254. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33255. for (kind in this._delayInfo) {
  33256. geometry._delayInfo = geometry._delayInfo || [];
  33257. geometry._delayInfo.push(kind);
  33258. }
  33259. // Bounding info
  33260. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33261. return geometry;
  33262. };
  33263. Geometry.prototype.serialize = function () {
  33264. var serializationObject = {};
  33265. serializationObject.id = this.id;
  33266. if (BABYLON.Tags.HasTags(this)) {
  33267. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33268. }
  33269. return serializationObject;
  33270. };
  33271. Geometry.prototype.serializeVerticeData = function () {
  33272. var serializationObject = this.serialize();
  33273. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33274. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33275. }
  33276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33277. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33278. }
  33279. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33280. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33281. }
  33282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33283. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33284. }
  33285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33286. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33287. }
  33288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33289. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33290. }
  33291. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33292. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33293. }
  33294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33295. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33296. }
  33297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33298. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33299. }
  33300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33301. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33302. serializationObject.matricesIndices._isExpanded = true;
  33303. }
  33304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33305. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33306. }
  33307. serializationObject.indices = this.getIndices();
  33308. return serializationObject;
  33309. };
  33310. // Statics
  33311. Geometry.ExtractFromMesh = function (mesh, id) {
  33312. var geometry = mesh._geometry;
  33313. if (!geometry) {
  33314. return null;
  33315. }
  33316. return geometry.copy(id);
  33317. };
  33318. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33319. // be aware Math.random() could cause collisions
  33320. Geometry.RandomId = function () {
  33321. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33322. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33323. return v.toString(16);
  33324. });
  33325. };
  33326. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33327. var scene = mesh.getScene();
  33328. // Geometry
  33329. var geometryId = parsedGeometry.geometryId;
  33330. if (geometryId) {
  33331. var geometry = scene.getGeometryByID(geometryId);
  33332. if (geometry) {
  33333. geometry.applyToMesh(mesh);
  33334. }
  33335. }
  33336. else if (parsedGeometry instanceof ArrayBuffer) {
  33337. var binaryInfo = mesh._binaryInfo;
  33338. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33339. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33340. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33341. }
  33342. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33343. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33344. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33345. }
  33346. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33347. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33348. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33349. }
  33350. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33351. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33352. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33353. }
  33354. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33355. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33356. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33357. }
  33358. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33359. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33360. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33361. }
  33362. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33363. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33364. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33365. }
  33366. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33367. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33368. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33369. }
  33370. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33371. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33372. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33373. }
  33374. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33375. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33376. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33377. }
  33378. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33379. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33380. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33381. }
  33382. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33383. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33384. mesh.setIndices(indicesData);
  33385. }
  33386. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33387. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33388. mesh.subMeshes = [];
  33389. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33390. var materialIndex = subMeshesData[(i * 5) + 0];
  33391. var verticesStart = subMeshesData[(i * 5) + 1];
  33392. var verticesCount = subMeshesData[(i * 5) + 2];
  33393. var indexStart = subMeshesData[(i * 5) + 3];
  33394. var indexCount = subMeshesData[(i * 5) + 4];
  33395. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33396. }
  33397. }
  33398. }
  33399. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33400. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33401. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33402. if (parsedGeometry.uvs) {
  33403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33404. }
  33405. if (parsedGeometry.uvs2) {
  33406. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33407. }
  33408. if (parsedGeometry.uvs3) {
  33409. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33410. }
  33411. if (parsedGeometry.uvs4) {
  33412. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33413. }
  33414. if (parsedGeometry.uvs5) {
  33415. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33416. }
  33417. if (parsedGeometry.uvs6) {
  33418. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33419. }
  33420. if (parsedGeometry.colors) {
  33421. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33422. }
  33423. if (parsedGeometry.matricesIndices) {
  33424. if (!parsedGeometry.matricesIndices._isExpanded) {
  33425. var floatIndices = [];
  33426. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33427. var matricesIndex = parsedGeometry.matricesIndices[i];
  33428. floatIndices.push(matricesIndex & 0x000000FF);
  33429. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33430. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33431. floatIndices.push(matricesIndex >> 24);
  33432. }
  33433. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33434. }
  33435. else {
  33436. delete parsedGeometry.matricesIndices._isExpanded;
  33437. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33438. }
  33439. }
  33440. if (parsedGeometry.matricesIndicesExtra) {
  33441. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33442. var floatIndices = [];
  33443. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33444. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33445. floatIndices.push(matricesIndex & 0x000000FF);
  33446. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33447. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33448. floatIndices.push(matricesIndex >> 24);
  33449. }
  33450. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33451. }
  33452. else {
  33453. delete parsedGeometry.matricesIndices._isExpanded;
  33454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33455. }
  33456. }
  33457. if (parsedGeometry.matricesWeights) {
  33458. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33459. }
  33460. if (parsedGeometry.matricesWeightsExtra) {
  33461. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33462. }
  33463. mesh.setIndices(parsedGeometry.indices);
  33464. }
  33465. // SubMeshes
  33466. if (parsedGeometry.subMeshes) {
  33467. mesh.subMeshes = [];
  33468. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33469. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33470. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33471. }
  33472. }
  33473. // Flat shading
  33474. if (mesh._shouldGenerateFlatShading) {
  33475. mesh.convertToFlatShadedMesh();
  33476. delete mesh._shouldGenerateFlatShading;
  33477. }
  33478. // Update
  33479. mesh.computeWorldMatrix(true);
  33480. // Octree
  33481. if (scene['_selectionOctree']) {
  33482. scene['_selectionOctree'].addMesh(mesh);
  33483. }
  33484. };
  33485. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33486. if (scene.getGeometryByID(parsedVertexData.id)) {
  33487. return null; // null since geometry could be something else than a box...
  33488. }
  33489. var geometry = new Geometry(parsedVertexData.id, scene);
  33490. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33491. if (parsedVertexData.delayLoadingFile) {
  33492. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33493. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33494. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33495. geometry._delayInfo = [];
  33496. if (parsedVertexData.hasUVs) {
  33497. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33498. }
  33499. if (parsedVertexData.hasUVs2) {
  33500. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33501. }
  33502. if (parsedVertexData.hasUVs3) {
  33503. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33504. }
  33505. if (parsedVertexData.hasUVs4) {
  33506. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33507. }
  33508. if (parsedVertexData.hasUVs5) {
  33509. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33510. }
  33511. if (parsedVertexData.hasUVs6) {
  33512. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33513. }
  33514. if (parsedVertexData.hasColors) {
  33515. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33516. }
  33517. if (parsedVertexData.hasMatricesIndices) {
  33518. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33519. }
  33520. if (parsedVertexData.hasMatricesWeights) {
  33521. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33522. }
  33523. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33524. }
  33525. else {
  33526. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33527. }
  33528. scene.pushGeometry(geometry, true);
  33529. return geometry;
  33530. };
  33531. return Geometry;
  33532. })();
  33533. BABYLON.Geometry = Geometry;
  33534. /////// Primitives //////////////////////////////////////////////
  33535. var Geometry;
  33536. (function (Geometry) {
  33537. var Primitives;
  33538. (function (Primitives) {
  33539. /// Abstract class
  33540. var _Primitive = (function (_super) {
  33541. __extends(_Primitive, _super);
  33542. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33543. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33544. this._canBeRegenerated = _canBeRegenerated;
  33545. this._beingRegenerated = true;
  33546. this.regenerate();
  33547. this._beingRegenerated = false;
  33548. }
  33549. _Primitive.prototype.canBeRegenerated = function () {
  33550. return this._canBeRegenerated;
  33551. };
  33552. _Primitive.prototype.regenerate = function () {
  33553. if (!this._canBeRegenerated) {
  33554. return;
  33555. }
  33556. this._beingRegenerated = true;
  33557. this.setAllVerticesData(this._regenerateVertexData(), false);
  33558. this._beingRegenerated = false;
  33559. };
  33560. _Primitive.prototype.asNewGeometry = function (id) {
  33561. return _super.prototype.copy.call(this, id);
  33562. };
  33563. // overrides
  33564. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33565. if (!this._beingRegenerated) {
  33566. return;
  33567. }
  33568. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33569. };
  33570. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33571. if (!this._beingRegenerated) {
  33572. return;
  33573. }
  33574. _super.prototype.setVerticesData.call(this, kind, data, false);
  33575. };
  33576. // to override
  33577. // protected
  33578. _Primitive.prototype._regenerateVertexData = function () {
  33579. throw new Error("Abstract method");
  33580. };
  33581. _Primitive.prototype.copy = function (id) {
  33582. throw new Error("Must be overriden in sub-classes.");
  33583. };
  33584. _Primitive.prototype.serialize = function () {
  33585. var serializationObject = _super.prototype.serialize.call(this);
  33586. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33587. return serializationObject;
  33588. };
  33589. return _Primitive;
  33590. })(Geometry);
  33591. Primitives._Primitive = _Primitive;
  33592. var Ribbon = (function (_super) {
  33593. __extends(Ribbon, _super);
  33594. // Members
  33595. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33596. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33597. _super.call(this, id, scene, canBeRegenerated, mesh);
  33598. this.pathArray = pathArray;
  33599. this.closeArray = closeArray;
  33600. this.closePath = closePath;
  33601. this.offset = offset;
  33602. this.side = side;
  33603. }
  33604. Ribbon.prototype._regenerateVertexData = function () {
  33605. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33606. };
  33607. Ribbon.prototype.copy = function (id) {
  33608. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33609. };
  33610. return Ribbon;
  33611. })(_Primitive);
  33612. Primitives.Ribbon = Ribbon;
  33613. var Box = (function (_super) {
  33614. __extends(Box, _super);
  33615. // Members
  33616. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33617. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33618. _super.call(this, id, scene, canBeRegenerated, mesh);
  33619. this.size = size;
  33620. this.side = side;
  33621. }
  33622. Box.prototype._regenerateVertexData = function () {
  33623. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33624. };
  33625. Box.prototype.copy = function (id) {
  33626. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33627. };
  33628. Box.prototype.serialize = function () {
  33629. var serializationObject = _super.prototype.serialize.call(this);
  33630. serializationObject.size = this.size;
  33631. return serializationObject;
  33632. };
  33633. Box.Parse = function (parsedBox, scene) {
  33634. if (scene.getGeometryByID(parsedBox.id)) {
  33635. return null; // null since geometry could be something else than a box...
  33636. }
  33637. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33638. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33639. scene.pushGeometry(box, true);
  33640. return box;
  33641. };
  33642. return Box;
  33643. })(_Primitive);
  33644. Primitives.Box = Box;
  33645. var Sphere = (function (_super) {
  33646. __extends(Sphere, _super);
  33647. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33648. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33649. _super.call(this, id, scene, canBeRegenerated, mesh);
  33650. this.segments = segments;
  33651. this.diameter = diameter;
  33652. this.side = side;
  33653. }
  33654. Sphere.prototype._regenerateVertexData = function () {
  33655. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33656. };
  33657. Sphere.prototype.copy = function (id) {
  33658. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33659. };
  33660. Sphere.prototype.serialize = function () {
  33661. var serializationObject = _super.prototype.serialize.call(this);
  33662. serializationObject.segments = this.segments;
  33663. serializationObject.diameter = this.diameter;
  33664. return serializationObject;
  33665. };
  33666. Sphere.Parse = function (parsedSphere, scene) {
  33667. if (scene.getGeometryByID(parsedSphere.id)) {
  33668. return null; // null since geometry could be something else than a sphere...
  33669. }
  33670. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33671. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33672. scene.pushGeometry(sphere, true);
  33673. return sphere;
  33674. };
  33675. return Sphere;
  33676. })(_Primitive);
  33677. Primitives.Sphere = Sphere;
  33678. var Disc = (function (_super) {
  33679. __extends(Disc, _super);
  33680. // Members
  33681. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33683. _super.call(this, id, scene, canBeRegenerated, mesh);
  33684. this.radius = radius;
  33685. this.tessellation = tessellation;
  33686. this.side = side;
  33687. }
  33688. Disc.prototype._regenerateVertexData = function () {
  33689. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33690. };
  33691. Disc.prototype.copy = function (id) {
  33692. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33693. };
  33694. return Disc;
  33695. })(_Primitive);
  33696. Primitives.Disc = Disc;
  33697. var Cylinder = (function (_super) {
  33698. __extends(Cylinder, _super);
  33699. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33700. if (subdivisions === void 0) { subdivisions = 1; }
  33701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33702. _super.call(this, id, scene, canBeRegenerated, mesh);
  33703. this.height = height;
  33704. this.diameterTop = diameterTop;
  33705. this.diameterBottom = diameterBottom;
  33706. this.tessellation = tessellation;
  33707. this.subdivisions = subdivisions;
  33708. this.side = side;
  33709. }
  33710. Cylinder.prototype._regenerateVertexData = function () {
  33711. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33712. };
  33713. Cylinder.prototype.copy = function (id) {
  33714. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33715. };
  33716. Cylinder.prototype.serialize = function () {
  33717. var serializationObject = _super.prototype.serialize.call(this);
  33718. serializationObject.height = this.height;
  33719. serializationObject.diameterTop = this.diameterTop;
  33720. serializationObject.diameterBottom = this.diameterBottom;
  33721. serializationObject.tessellation = this.tessellation;
  33722. return serializationObject;
  33723. };
  33724. Cylinder.Parse = function (parsedCylinder, scene) {
  33725. if (scene.getGeometryByID(parsedCylinder.id)) {
  33726. return null; // null since geometry could be something else than a cylinder...
  33727. }
  33728. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33729. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33730. scene.pushGeometry(cylinder, true);
  33731. return cylinder;
  33732. };
  33733. return Cylinder;
  33734. })(_Primitive);
  33735. Primitives.Cylinder = Cylinder;
  33736. var Torus = (function (_super) {
  33737. __extends(Torus, _super);
  33738. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33739. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33740. _super.call(this, id, scene, canBeRegenerated, mesh);
  33741. this.diameter = diameter;
  33742. this.thickness = thickness;
  33743. this.tessellation = tessellation;
  33744. this.side = side;
  33745. }
  33746. Torus.prototype._regenerateVertexData = function () {
  33747. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33748. };
  33749. Torus.prototype.copy = function (id) {
  33750. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33751. };
  33752. Torus.prototype.serialize = function () {
  33753. var serializationObject = _super.prototype.serialize.call(this);
  33754. serializationObject.diameter = this.diameter;
  33755. serializationObject.thickness = this.thickness;
  33756. serializationObject.tessellation = this.tessellation;
  33757. return serializationObject;
  33758. };
  33759. Torus.Parse = function (parsedTorus, scene) {
  33760. if (scene.getGeometryByID(parsedTorus.id)) {
  33761. return null; // null since geometry could be something else than a torus...
  33762. }
  33763. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33764. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33765. scene.pushGeometry(torus, true);
  33766. return torus;
  33767. };
  33768. return Torus;
  33769. })(_Primitive);
  33770. Primitives.Torus = Torus;
  33771. var Ground = (function (_super) {
  33772. __extends(Ground, _super);
  33773. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33774. _super.call(this, id, scene, canBeRegenerated, mesh);
  33775. this.width = width;
  33776. this.height = height;
  33777. this.subdivisions = subdivisions;
  33778. }
  33779. Ground.prototype._regenerateVertexData = function () {
  33780. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33781. };
  33782. Ground.prototype.copy = function (id) {
  33783. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33784. };
  33785. Ground.prototype.serialize = function () {
  33786. var serializationObject = _super.prototype.serialize.call(this);
  33787. serializationObject.width = this.width;
  33788. serializationObject.height = this.height;
  33789. serializationObject.subdivisions = this.subdivisions;
  33790. return serializationObject;
  33791. };
  33792. Ground.Parse = function (parsedGround, scene) {
  33793. if (scene.getGeometryByID(parsedGround.id)) {
  33794. return null; // null since geometry could be something else than a ground...
  33795. }
  33796. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33797. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33798. scene.pushGeometry(ground, true);
  33799. return ground;
  33800. };
  33801. return Ground;
  33802. })(_Primitive);
  33803. Primitives.Ground = Ground;
  33804. var TiledGround = (function (_super) {
  33805. __extends(TiledGround, _super);
  33806. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  33807. _super.call(this, id, scene, canBeRegenerated, mesh);
  33808. this.xmin = xmin;
  33809. this.zmin = zmin;
  33810. this.xmax = xmax;
  33811. this.zmax = zmax;
  33812. this.subdivisions = subdivisions;
  33813. this.precision = precision;
  33814. }
  33815. TiledGround.prototype._regenerateVertexData = function () {
  33816. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33817. };
  33818. TiledGround.prototype.copy = function (id) {
  33819. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33820. };
  33821. return TiledGround;
  33822. })(_Primitive);
  33823. Primitives.TiledGround = TiledGround;
  33824. var Plane = (function (_super) {
  33825. __extends(Plane, _super);
  33826. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  33827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33828. _super.call(this, id, scene, canBeRegenerated, mesh);
  33829. this.size = size;
  33830. this.side = side;
  33831. }
  33832. Plane.prototype._regenerateVertexData = function () {
  33833. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33834. };
  33835. Plane.prototype.copy = function (id) {
  33836. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33837. };
  33838. Plane.prototype.serialize = function () {
  33839. var serializationObject = _super.prototype.serialize.call(this);
  33840. serializationObject.size = this.size;
  33841. return serializationObject;
  33842. };
  33843. Plane.Parse = function (parsedPlane, scene) {
  33844. if (scene.getGeometryByID(parsedPlane.id)) {
  33845. return null; // null since geometry could be something else than a ground...
  33846. }
  33847. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33848. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33849. scene.pushGeometry(plane, true);
  33850. return plane;
  33851. };
  33852. return Plane;
  33853. })(_Primitive);
  33854. Primitives.Plane = Plane;
  33855. var TorusKnot = (function (_super) {
  33856. __extends(TorusKnot, _super);
  33857. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33859. _super.call(this, id, scene, canBeRegenerated, mesh);
  33860. this.radius = radius;
  33861. this.tube = tube;
  33862. this.radialSegments = radialSegments;
  33863. this.tubularSegments = tubularSegments;
  33864. this.p = p;
  33865. this.q = q;
  33866. this.side = side;
  33867. }
  33868. TorusKnot.prototype._regenerateVertexData = function () {
  33869. 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 });
  33870. };
  33871. TorusKnot.prototype.copy = function (id) {
  33872. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33873. };
  33874. TorusKnot.prototype.serialize = function () {
  33875. var serializationObject = _super.prototype.serialize.call(this);
  33876. serializationObject.radius = this.radius;
  33877. serializationObject.tube = this.tube;
  33878. serializationObject.radialSegments = this.radialSegments;
  33879. serializationObject.tubularSegments = this.tubularSegments;
  33880. serializationObject.p = this.p;
  33881. serializationObject.q = this.q;
  33882. return serializationObject;
  33883. };
  33884. ;
  33885. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33886. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33887. return null; // null since geometry could be something else than a ground...
  33888. }
  33889. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33890. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33891. scene.pushGeometry(torusKnot, true);
  33892. return torusKnot;
  33893. };
  33894. return TorusKnot;
  33895. })(_Primitive);
  33896. Primitives.TorusKnot = TorusKnot;
  33897. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33898. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33899. })(BABYLON || (BABYLON = {}));
  33900. var BABYLON;
  33901. (function (BABYLON) {
  33902. var GroundMesh = (function (_super) {
  33903. __extends(GroundMesh, _super);
  33904. function GroundMesh(name, scene) {
  33905. _super.call(this, name, scene);
  33906. this.generateOctree = false;
  33907. this._worldInverse = new BABYLON.Matrix();
  33908. }
  33909. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33910. get: function () {
  33911. return this._subdivisions;
  33912. },
  33913. enumerable: true,
  33914. configurable: true
  33915. });
  33916. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33917. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33918. this._subdivisions = chunksCount;
  33919. this.subdivide(this._subdivisions);
  33920. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33921. };
  33922. /**
  33923. * Returns a height (y) value in the Worl system :
  33924. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33925. * Returns the ground y position if (x, z) are outside the ground surface.
  33926. * Not pertinent if the ground is rotated.
  33927. */
  33928. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33929. // express x and y in the ground local system
  33930. x -= this.position.x;
  33931. z -= this.position.z;
  33932. x /= this.scaling.x;
  33933. z /= this.scaling.z;
  33934. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33935. return this.position.y;
  33936. }
  33937. if (!this._heightQuads || this._heightQuads.length == 0) {
  33938. this._initHeightQuads();
  33939. this._computeHeightQuads();
  33940. }
  33941. var facet = this._getFacetAt(x, z);
  33942. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33943. // return y in the World system
  33944. return y * this.scaling.y + this.position.y;
  33945. };
  33946. /**
  33947. * Returns a normalized vector (Vector3) orthogonal to the ground
  33948. * at the ground coordinates (x, z) expressed in the World system.
  33949. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  33950. * Not pertinent if the ground is rotated.
  33951. */
  33952. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33953. var normal = new BABYLON.Vector3(0, 1, 0);
  33954. this.getNormalAtCoordinatesToRef(x, z, normal);
  33955. return normal;
  33956. };
  33957. /**
  33958. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33959. * at the ground coordinates (x, z) expressed in the World system.
  33960. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33961. * Not pertinent if the ground is rotated.
  33962. */
  33963. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33964. // express x and y in the ground local system
  33965. x -= this.position.x;
  33966. z -= this.position.z;
  33967. x /= this.scaling.x;
  33968. z /= this.scaling.z;
  33969. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33970. return;
  33971. }
  33972. if (!this._heightQuads || this._heightQuads.length == 0) {
  33973. this._initHeightQuads();
  33974. this._computeHeightQuads();
  33975. }
  33976. var facet = this._getFacetAt(x, z);
  33977. ref.x = facet.x;
  33978. ref.y = facet.y;
  33979. ref.z = facet.z;
  33980. };
  33981. /**
  33982. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33983. * if the ground has been updated.
  33984. * This can be used in the render loop
  33985. */
  33986. GroundMesh.prototype.updateCoordinateHeights = function () {
  33987. if (!this._heightQuads || this._heightQuads.length == 0) {
  33988. this._initHeightQuads();
  33989. }
  33990. this._computeHeightQuads();
  33991. };
  33992. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33993. GroundMesh.prototype._getFacetAt = function (x, z) {
  33994. // retrieve col and row from x, z coordinates in the ground local system
  33995. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  33996. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  33997. var quad = this._heightQuads[row * this._subdivisions + col];
  33998. var facet;
  33999. if (z < quad.slope.x * x + quad.slope.y) {
  34000. facet = quad.facet1;
  34001. }
  34002. else {
  34003. facet = quad.facet2;
  34004. }
  34005. return facet;
  34006. };
  34007. // Creates and populates the heightMap array with "facet" elements :
  34008. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34009. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34010. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34011. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34012. GroundMesh.prototype._initHeightQuads = function () {
  34013. this._heightQuads = new Array();
  34014. for (var row = 0; row < this._subdivisions; row++) {
  34015. for (var col = 0; col < this._subdivisions; col++) {
  34016. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34017. this._heightQuads[row * this._subdivisions + col] = quad;
  34018. }
  34019. }
  34020. };
  34021. // Compute each quad element values and update the the heightMap array :
  34022. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34023. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34024. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34025. GroundMesh.prototype._computeHeightQuads = function () {
  34026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34027. var v1 = BABYLON.Tmp.Vector3[3];
  34028. var v2 = BABYLON.Tmp.Vector3[2];
  34029. var v3 = BABYLON.Tmp.Vector3[1];
  34030. var v4 = BABYLON.Tmp.Vector3[0];
  34031. var v1v2 = BABYLON.Tmp.Vector3[4];
  34032. var v1v3 = BABYLON.Tmp.Vector3[5];
  34033. var v1v4 = BABYLON.Tmp.Vector3[6];
  34034. var norm1 = BABYLON.Tmp.Vector3[7];
  34035. var norm2 = BABYLON.Tmp.Vector3[8];
  34036. var i = 0;
  34037. var j = 0;
  34038. var k = 0;
  34039. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34040. var h = 0;
  34041. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34042. var d2 = 0;
  34043. for (var row = 0; row < this._subdivisions; row++) {
  34044. for (var col = 0; col < this._subdivisions; col++) {
  34045. i = col * 3;
  34046. j = row * (this._subdivisions + 1) * 3;
  34047. k = (row + 1) * (this._subdivisions + 1) * 3;
  34048. v1.x = positions[j + i];
  34049. v1.y = positions[j + i + 1];
  34050. v1.z = positions[j + i + 2];
  34051. v2.x = positions[j + i + 3];
  34052. v2.y = positions[j + i + 4];
  34053. v2.z = positions[j + i + 5];
  34054. v3.x = positions[k + i];
  34055. v3.y = positions[k + i + 1];
  34056. v3.z = positions[k + i + 2];
  34057. v4.x = positions[k + i + 3];
  34058. v4.y = positions[k + i + 4];
  34059. v4.z = positions[k + i + 5];
  34060. // 2D slope V1V4
  34061. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34062. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34063. // facet equations :
  34064. // we compute each facet normal vector
  34065. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34066. // we compute the value d by applying the equation to v1 which belongs to the plane
  34067. // then we store the facet equation in a Vector4
  34068. v2.subtractToRef(v1, v1v2);
  34069. v3.subtractToRef(v1, v1v3);
  34070. v4.subtractToRef(v1, v1v4);
  34071. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34072. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34073. norm1.normalize();
  34074. norm2.normalize();
  34075. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34076. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34077. var quad = this._heightQuads[row * this._subdivisions + col];
  34078. quad.slope.copyFromFloats(cd, h);
  34079. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34080. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34081. }
  34082. }
  34083. };
  34084. return GroundMesh;
  34085. })(BABYLON.Mesh);
  34086. BABYLON.GroundMesh = GroundMesh;
  34087. })(BABYLON || (BABYLON = {}));
  34088. var BABYLON;
  34089. (function (BABYLON) {
  34090. var LinesMesh = (function (_super) {
  34091. __extends(LinesMesh, _super);
  34092. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34093. if (parent === void 0) { parent = null; }
  34094. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34095. this.color = new BABYLON.Color3(1, 1, 1);
  34096. this.alpha = 1;
  34097. this._positionBuffer = {};
  34098. if (source) {
  34099. this.color = source.color.clone();
  34100. this.alpha = source.alpha;
  34101. }
  34102. this._intersectionThreshold = 0.1;
  34103. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34104. attributes: [BABYLON.VertexBuffer.PositionKind],
  34105. uniforms: ["worldViewProjection", "color"],
  34106. needAlphaBlending: true
  34107. });
  34108. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34109. }
  34110. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34111. /**
  34112. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34113. * This margin is expressed in world space coordinates, so its value may vary.
  34114. * Default value is 0.1
  34115. * @returns the intersection Threshold value.
  34116. */
  34117. get: function () {
  34118. return this._intersectionThreshold;
  34119. },
  34120. /**
  34121. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34122. * This margin is expressed in world space coordinates, so its value may vary.
  34123. * @param value the new threshold to apply
  34124. */
  34125. set: function (value) {
  34126. if (this._intersectionThreshold === value) {
  34127. return;
  34128. }
  34129. this._intersectionThreshold = value;
  34130. if (this.geometry) {
  34131. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34132. }
  34133. },
  34134. enumerable: true,
  34135. configurable: true
  34136. });
  34137. Object.defineProperty(LinesMesh.prototype, "material", {
  34138. get: function () {
  34139. return this._colorShader;
  34140. },
  34141. enumerable: true,
  34142. configurable: true
  34143. });
  34144. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34145. get: function () {
  34146. return false;
  34147. },
  34148. enumerable: true,
  34149. configurable: true
  34150. });
  34151. LinesMesh.prototype.createInstance = function (name) {
  34152. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34153. return null;
  34154. };
  34155. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34156. var engine = this.getScene().getEngine();
  34157. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34158. // VBOs
  34159. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34160. // Color
  34161. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34162. };
  34163. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34164. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34165. return;
  34166. }
  34167. var engine = this.getScene().getEngine();
  34168. // Draw order
  34169. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34170. };
  34171. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34172. this._colorShader.dispose();
  34173. _super.prototype.dispose.call(this, doNotRecurse);
  34174. };
  34175. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34176. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34177. };
  34178. return LinesMesh;
  34179. })(BABYLON.Mesh);
  34180. BABYLON.LinesMesh = LinesMesh;
  34181. })(BABYLON || (BABYLON = {}));
  34182. var BABYLON;
  34183. (function (BABYLON) {
  34184. var DefaultLoadingScreen = (function () {
  34185. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34186. var _this = this;
  34187. if (_loadingText === void 0) { _loadingText = ""; }
  34188. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34189. this._renderingCanvas = _renderingCanvas;
  34190. this._loadingText = _loadingText;
  34191. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34192. // Resize
  34193. this._resizeLoadingUI = function () {
  34194. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34195. _this._loadingDiv.style.position = "absolute";
  34196. _this._loadingDiv.style.left = canvasRect.left + "px";
  34197. _this._loadingDiv.style.top = canvasRect.top + "px";
  34198. _this._loadingDiv.style.width = canvasRect.width + "px";
  34199. _this._loadingDiv.style.height = canvasRect.height + "px";
  34200. };
  34201. }
  34202. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34203. var _this = this;
  34204. if (this._loadingDiv) {
  34205. // Do not add a loading screen if there is already one
  34206. return;
  34207. }
  34208. this._loadingDiv = document.createElement("div");
  34209. this._loadingDiv.id = "babylonjsLoadingDiv";
  34210. this._loadingDiv.style.opacity = "0";
  34211. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34212. // Loading text
  34213. this._loadingTextDiv = document.createElement("div");
  34214. this._loadingTextDiv.style.position = "absolute";
  34215. this._loadingTextDiv.style.left = "0";
  34216. this._loadingTextDiv.style.top = "50%";
  34217. this._loadingTextDiv.style.marginTop = "80px";
  34218. this._loadingTextDiv.style.width = "100%";
  34219. this._loadingTextDiv.style.height = "20px";
  34220. this._loadingTextDiv.style.fontFamily = "Arial";
  34221. this._loadingTextDiv.style.fontSize = "14px";
  34222. this._loadingTextDiv.style.color = "white";
  34223. this._loadingTextDiv.style.textAlign = "center";
  34224. this._loadingTextDiv.innerHTML = "Loading";
  34225. this._loadingDiv.appendChild(this._loadingTextDiv);
  34226. //set the predefined text
  34227. this._loadingTextDiv.innerHTML = this._loadingText;
  34228. // Loading img
  34229. var imgBack = new Image();
  34230. 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==";
  34231. imgBack.style.position = "absolute";
  34232. imgBack.style.left = "50%";
  34233. imgBack.style.top = "50%";
  34234. imgBack.style.marginLeft = "-50px";
  34235. imgBack.style.marginTop = "-50px";
  34236. imgBack.style.transition = "transform 1.0s ease";
  34237. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34238. var deg = 360;
  34239. var onTransitionEnd = function () {
  34240. deg += 360;
  34241. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34242. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34243. };
  34244. imgBack.addEventListener("transitionend", onTransitionEnd);
  34245. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34246. this._loadingDiv.appendChild(imgBack);
  34247. // front image
  34248. var imgFront = new Image();
  34249. 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=";
  34250. imgFront.style.position = "absolute";
  34251. imgFront.style.left = "50%";
  34252. imgFront.style.top = "50%";
  34253. imgFront.style.marginLeft = "-50px";
  34254. imgFront.style.marginTop = "-50px";
  34255. this._loadingDiv.appendChild(imgFront);
  34256. this._resizeLoadingUI();
  34257. window.addEventListener("resize", this._resizeLoadingUI);
  34258. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34259. document.body.appendChild(this._loadingDiv);
  34260. setTimeout(function () {
  34261. _this._loadingDiv.style.opacity = "1";
  34262. imgBack.style.transform = "rotateZ(360deg)";
  34263. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34264. }, 0);
  34265. };
  34266. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34267. var _this = this;
  34268. if (!this._loadingDiv) {
  34269. return;
  34270. }
  34271. var onTransitionEnd = function () {
  34272. if (!_this._loadingDiv) {
  34273. return;
  34274. }
  34275. document.body.removeChild(_this._loadingDiv);
  34276. window.removeEventListener("resize", _this._resizeLoadingUI);
  34277. _this._loadingDiv = null;
  34278. };
  34279. this._loadingDiv.style.opacity = "0";
  34280. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34281. };
  34282. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34283. set: function (text) {
  34284. this._loadingText = text;
  34285. if (this._loadingTextDiv) {
  34286. this._loadingTextDiv.innerHTML = this._loadingText;
  34287. }
  34288. },
  34289. enumerable: true,
  34290. configurable: true
  34291. });
  34292. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34293. get: function () {
  34294. return this._loadingDivBackgroundColor;
  34295. },
  34296. set: function (color) {
  34297. this._loadingDivBackgroundColor = color;
  34298. if (!this._loadingDiv) {
  34299. return;
  34300. }
  34301. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34302. },
  34303. enumerable: true,
  34304. configurable: true
  34305. });
  34306. return DefaultLoadingScreen;
  34307. })();
  34308. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34309. })(BABYLON || (BABYLON = {}));
  34310. var BABYLON;
  34311. (function (BABYLON) {
  34312. var AudioEngine = (function () {
  34313. function AudioEngine() {
  34314. this._audioContext = null;
  34315. this._audioContextInitialized = false;
  34316. this.canUseWebAudio = false;
  34317. this.WarnedWebAudioUnsupported = false;
  34318. this.unlocked = false;
  34319. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34320. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34321. this.canUseWebAudio = true;
  34322. }
  34323. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34324. this._unlockiOSaudio();
  34325. }
  34326. else {
  34327. this.unlocked = true;
  34328. }
  34329. }
  34330. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34331. get: function () {
  34332. if (!this._audioContextInitialized) {
  34333. this._initializeAudioContext();
  34334. }
  34335. return this._audioContext;
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. AudioEngine.prototype._unlockiOSaudio = function () {
  34341. var _this = this;
  34342. var unlockaudio = function () {
  34343. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34344. var source = _this.audioContext.createBufferSource();
  34345. source.buffer = buffer;
  34346. source.connect(_this.audioContext.destination);
  34347. source.start(0);
  34348. setTimeout(function () {
  34349. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34350. _this.unlocked = true;
  34351. window.removeEventListener('touchend', unlockaudio, false);
  34352. if (_this.onAudioUnlocked) {
  34353. _this.onAudioUnlocked();
  34354. }
  34355. }
  34356. }, 0);
  34357. };
  34358. window.addEventListener('touchend', unlockaudio, false);
  34359. };
  34360. AudioEngine.prototype._initializeAudioContext = function () {
  34361. try {
  34362. if (this.canUseWebAudio) {
  34363. this._audioContext = new AudioContext();
  34364. // create a global volume gain node
  34365. this.masterGain = this._audioContext.createGain();
  34366. this.masterGain.gain.value = 1;
  34367. this.masterGain.connect(this._audioContext.destination);
  34368. this._audioContextInitialized = true;
  34369. }
  34370. }
  34371. catch (e) {
  34372. this.canUseWebAudio = false;
  34373. BABYLON.Tools.Error("Web Audio: " + e.message);
  34374. }
  34375. };
  34376. AudioEngine.prototype.dispose = function () {
  34377. if (this.canUseWebAudio && this._audioContextInitialized) {
  34378. if (this._connectedAnalyser) {
  34379. this._connectedAnalyser.stopDebugCanvas();
  34380. this._connectedAnalyser.dispose();
  34381. this.masterGain.disconnect();
  34382. this.masterGain.connect(this._audioContext.destination);
  34383. this._connectedAnalyser = null;
  34384. }
  34385. this.masterGain.gain.value = 1;
  34386. }
  34387. this.WarnedWebAudioUnsupported = false;
  34388. };
  34389. AudioEngine.prototype.getGlobalVolume = function () {
  34390. if (this.canUseWebAudio && this._audioContextInitialized) {
  34391. return this.masterGain.gain.value;
  34392. }
  34393. else {
  34394. return -1;
  34395. }
  34396. };
  34397. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34398. if (this.canUseWebAudio && this._audioContextInitialized) {
  34399. this.masterGain.gain.value = newVolume;
  34400. }
  34401. };
  34402. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34403. if (this._connectedAnalyser) {
  34404. this._connectedAnalyser.stopDebugCanvas();
  34405. }
  34406. if (this.canUseWebAudio && this._audioContextInitialized) {
  34407. this._connectedAnalyser = analyser;
  34408. this.masterGain.disconnect();
  34409. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34410. }
  34411. };
  34412. return AudioEngine;
  34413. })();
  34414. BABYLON.AudioEngine = AudioEngine;
  34415. })(BABYLON || (BABYLON = {}));
  34416. var BABYLON;
  34417. (function (BABYLON) {
  34418. var Sound = (function () {
  34419. /**
  34420. * Create a sound and attach it to a scene
  34421. * @param name Name of your sound
  34422. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34423. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34424. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34425. */
  34426. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34427. var _this = this;
  34428. this.autoplay = false;
  34429. this.loop = false;
  34430. this.useCustomAttenuation = false;
  34431. this.spatialSound = false;
  34432. this.refDistance = 1;
  34433. this.rolloffFactor = 1;
  34434. this.maxDistance = 100;
  34435. this.distanceModel = "linear";
  34436. this._panningModel = "equalpower";
  34437. this._playbackRate = 1;
  34438. this._streaming = false;
  34439. this._startTime = 0;
  34440. this._startOffset = 0;
  34441. this._position = BABYLON.Vector3.Zero();
  34442. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34443. this._volume = 1;
  34444. this._isLoaded = false;
  34445. this._isReadyToPlay = false;
  34446. this.isPlaying = false;
  34447. this.isPaused = false;
  34448. this._isDirectional = false;
  34449. // Used if you'd like to create a directional sound.
  34450. // If not set, the sound will be omnidirectional
  34451. this._coneInnerAngle = 360;
  34452. this._coneOuterAngle = 360;
  34453. this._coneOuterGain = 0;
  34454. this._isOutputConnected = false;
  34455. this.name = name;
  34456. this._scene = scene;
  34457. this._readyToPlayCallback = readyToPlayCallback;
  34458. // Default custom attenuation function is a linear attenuation
  34459. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34460. if (currentDistance < maxDistance) {
  34461. return currentVolume * (1 - currentDistance / maxDistance);
  34462. }
  34463. else {
  34464. return 0;
  34465. }
  34466. };
  34467. if (options) {
  34468. this.autoplay = options.autoplay || false;
  34469. this.loop = options.loop || false;
  34470. // if volume === 0, we need another way to check this option
  34471. if (options.volume !== undefined) {
  34472. this._volume = options.volume;
  34473. }
  34474. this.spatialSound = options.spatialSound || false;
  34475. this.maxDistance = options.maxDistance || 100;
  34476. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34477. this.rolloffFactor = options.rolloffFactor || 1;
  34478. this.refDistance = options.refDistance || 1;
  34479. this.distanceModel = options.distanceModel || "linear";
  34480. this._playbackRate = options.playbackRate || 1;
  34481. this._streaming = options.streaming || false;
  34482. }
  34483. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34484. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34485. this._soundGain.gain.value = this._volume;
  34486. this._inputAudioNode = this._soundGain;
  34487. this._ouputAudioNode = this._soundGain;
  34488. if (this.spatialSound) {
  34489. this._createSpatialParameters();
  34490. }
  34491. this._scene.mainSoundTrack.AddSound(this);
  34492. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34493. if (urlOrArrayBuffer) {
  34494. // If it's an URL
  34495. if (typeof (urlOrArrayBuffer) === "string") {
  34496. // Loading sound using XHR2
  34497. if (!this._streaming) {
  34498. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34499. }
  34500. else {
  34501. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34502. this._htmlAudioElement.controls = false;
  34503. this._htmlAudioElement.loop = this.loop;
  34504. this._htmlAudioElement.crossOrigin = "anonymous";
  34505. this._htmlAudioElement.preload = "auto";
  34506. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34507. _this._isReadyToPlay = true;
  34508. if (_this.autoplay) {
  34509. _this.play();
  34510. }
  34511. if (_this._readyToPlayCallback) {
  34512. _this._readyToPlayCallback();
  34513. }
  34514. });
  34515. document.body.appendChild(this._htmlAudioElement);
  34516. }
  34517. }
  34518. else {
  34519. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34520. if (urlOrArrayBuffer.byteLength > 0) {
  34521. this._soundLoaded(urlOrArrayBuffer);
  34522. }
  34523. }
  34524. else {
  34525. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34526. }
  34527. }
  34528. }
  34529. }
  34530. else {
  34531. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34532. this._scene.mainSoundTrack.AddSound(this);
  34533. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34534. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34535. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34536. }
  34537. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34538. if (this._readyToPlayCallback) {
  34539. window.setTimeout(function () {
  34540. _this._readyToPlayCallback();
  34541. }, 1000);
  34542. }
  34543. }
  34544. }
  34545. Sound.prototype.dispose = function () {
  34546. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34547. if (this.isPlaying) {
  34548. this.stop();
  34549. }
  34550. this._isReadyToPlay = false;
  34551. if (this.soundTrackId === -1) {
  34552. this._scene.mainSoundTrack.RemoveSound(this);
  34553. }
  34554. else {
  34555. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34556. }
  34557. if (this._soundGain) {
  34558. this._soundGain.disconnect();
  34559. this._soundGain = null;
  34560. }
  34561. if (this._soundPanner) {
  34562. this._soundPanner.disconnect();
  34563. this._soundPanner = null;
  34564. }
  34565. if (this._soundSource) {
  34566. this._soundSource.disconnect();
  34567. this._soundSource = null;
  34568. }
  34569. this._audioBuffer = null;
  34570. if (this._htmlAudioElement) {
  34571. this._htmlAudioElement.pause();
  34572. this._htmlAudioElement.src = "";
  34573. document.body.removeChild(this._htmlAudioElement);
  34574. }
  34575. if (this._connectedMesh) {
  34576. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34577. this._connectedMesh = null;
  34578. }
  34579. }
  34580. };
  34581. Sound.prototype._soundLoaded = function (audioData) {
  34582. var _this = this;
  34583. this._isLoaded = true;
  34584. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34585. _this._audioBuffer = buffer;
  34586. _this._isReadyToPlay = true;
  34587. if (_this.autoplay) {
  34588. _this.play();
  34589. }
  34590. if (_this._readyToPlayCallback) {
  34591. _this._readyToPlayCallback();
  34592. }
  34593. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34594. };
  34595. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34596. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34597. this._audioBuffer = audioBuffer;
  34598. this._isReadyToPlay = true;
  34599. }
  34600. };
  34601. Sound.prototype.updateOptions = function (options) {
  34602. if (options) {
  34603. this.loop = options.loop || this.loop;
  34604. this.maxDistance = options.maxDistance || this.maxDistance;
  34605. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34606. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34607. this.refDistance = options.refDistance || this.refDistance;
  34608. this.distanceModel = options.distanceModel || this.distanceModel;
  34609. this._playbackRate = options.playbackRate || this._playbackRate;
  34610. this._updateSpatialParameters();
  34611. if (this.isPlaying) {
  34612. if (this._streaming) {
  34613. this._htmlAudioElement.playbackRate = this._playbackRate;
  34614. }
  34615. else {
  34616. this._soundSource.playbackRate.value = this._playbackRate;
  34617. }
  34618. }
  34619. }
  34620. };
  34621. Sound.prototype._createSpatialParameters = function () {
  34622. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34623. if (this._scene.headphone) {
  34624. this._panningModel = "HRTF";
  34625. }
  34626. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34627. this._updateSpatialParameters();
  34628. this._soundPanner.connect(this._ouputAudioNode);
  34629. this._inputAudioNode = this._soundPanner;
  34630. }
  34631. };
  34632. Sound.prototype._updateSpatialParameters = function () {
  34633. if (this.spatialSound) {
  34634. if (this.useCustomAttenuation) {
  34635. // Tricks to disable in a way embedded Web Audio attenuation
  34636. this._soundPanner.distanceModel = "linear";
  34637. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34638. this._soundPanner.refDistance = 1;
  34639. this._soundPanner.rolloffFactor = 1;
  34640. this._soundPanner.panningModel = this._panningModel;
  34641. }
  34642. else {
  34643. this._soundPanner.distanceModel = this.distanceModel;
  34644. this._soundPanner.maxDistance = this.maxDistance;
  34645. this._soundPanner.refDistance = this.refDistance;
  34646. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34647. this._soundPanner.panningModel = this._panningModel;
  34648. }
  34649. }
  34650. };
  34651. Sound.prototype.switchPanningModelToHRTF = function () {
  34652. this._panningModel = "HRTF";
  34653. this._switchPanningModel();
  34654. };
  34655. Sound.prototype.switchPanningModelToEqualPower = function () {
  34656. this._panningModel = "equalpower";
  34657. this._switchPanningModel();
  34658. };
  34659. Sound.prototype._switchPanningModel = function () {
  34660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34661. this._soundPanner.panningModel = this._panningModel;
  34662. }
  34663. };
  34664. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34665. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34666. if (this._isOutputConnected) {
  34667. this._ouputAudioNode.disconnect();
  34668. }
  34669. this._ouputAudioNode.connect(soundTrackAudioNode);
  34670. this._isOutputConnected = true;
  34671. }
  34672. };
  34673. /**
  34674. * Transform this sound into a directional source
  34675. * @param coneInnerAngle Size of the inner cone in degree
  34676. * @param coneOuterAngle Size of the outer cone in degree
  34677. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34678. */
  34679. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34680. if (coneOuterAngle < coneInnerAngle) {
  34681. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34682. return;
  34683. }
  34684. this._coneInnerAngle = coneInnerAngle;
  34685. this._coneOuterAngle = coneOuterAngle;
  34686. this._coneOuterGain = coneOuterGain;
  34687. this._isDirectional = true;
  34688. if (this.isPlaying && this.loop) {
  34689. this.stop();
  34690. this.play();
  34691. }
  34692. };
  34693. Sound.prototype.setPosition = function (newPosition) {
  34694. this._position = newPosition;
  34695. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34696. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34697. }
  34698. };
  34699. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34700. this._localDirection = newLocalDirection;
  34701. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34702. this._updateDirection();
  34703. }
  34704. };
  34705. Sound.prototype._updateDirection = function () {
  34706. var mat = this._connectedMesh.getWorldMatrix();
  34707. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34708. direction.normalize();
  34709. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34710. };
  34711. Sound.prototype.updateDistanceFromListener = function () {
  34712. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34713. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34714. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34715. }
  34716. };
  34717. Sound.prototype.setAttenuationFunction = function (callback) {
  34718. this._customAttenuationFunction = callback;
  34719. };
  34720. /**
  34721. * Play the sound
  34722. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34723. * @param offset (optional) Start the sound setting it at a specific time
  34724. */
  34725. Sound.prototype.play = function (time, offset) {
  34726. var _this = this;
  34727. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34728. try {
  34729. if (this._startOffset < 0) {
  34730. time = -this._startOffset;
  34731. this._startOffset = 0;
  34732. }
  34733. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34734. if (!this._soundSource || !this._streamingSource) {
  34735. if (this.spatialSound) {
  34736. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34737. if (this._isDirectional) {
  34738. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34739. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34740. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34741. if (this._connectedMesh) {
  34742. this._updateDirection();
  34743. }
  34744. else {
  34745. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34746. }
  34747. }
  34748. }
  34749. }
  34750. if (this._streaming) {
  34751. if (!this._streamingSource) {
  34752. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34753. this._htmlAudioElement.onended = function () { _this._onended(); };
  34754. this._htmlAudioElement.playbackRate = this._playbackRate;
  34755. }
  34756. this._streamingSource.disconnect();
  34757. this._streamingSource.connect(this._inputAudioNode);
  34758. this._htmlAudioElement.play();
  34759. }
  34760. else {
  34761. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34762. this._soundSource.buffer = this._audioBuffer;
  34763. this._soundSource.connect(this._inputAudioNode);
  34764. this._soundSource.loop = this.loop;
  34765. this._soundSource.playbackRate.value = this._playbackRate;
  34766. this._soundSource.onended = function () { _this._onended(); };
  34767. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  34768. }
  34769. this._startTime = startTime;
  34770. this.isPlaying = true;
  34771. this.isPaused = false;
  34772. }
  34773. catch (ex) {
  34774. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34775. }
  34776. }
  34777. };
  34778. Sound.prototype._onended = function () {
  34779. this.isPlaying = false;
  34780. if (this.onended) {
  34781. this.onended();
  34782. }
  34783. };
  34784. /**
  34785. * Stop the sound
  34786. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34787. */
  34788. Sound.prototype.stop = function (time) {
  34789. if (this.isPlaying) {
  34790. if (this._streaming) {
  34791. this._htmlAudioElement.pause();
  34792. // Test needed for Firefox or it will generate an Invalid State Error
  34793. if (this._htmlAudioElement.currentTime > 0) {
  34794. this._htmlAudioElement.currentTime = 0;
  34795. }
  34796. }
  34797. else {
  34798. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34799. this._soundSource.stop(stopTime);
  34800. this._soundSource.onended = null;
  34801. if (!this.isPaused) {
  34802. this._startOffset = 0;
  34803. }
  34804. }
  34805. this.isPlaying = false;
  34806. }
  34807. };
  34808. Sound.prototype.pause = function () {
  34809. if (this.isPlaying) {
  34810. this.isPaused = true;
  34811. if (this._streaming) {
  34812. this._htmlAudioElement.pause();
  34813. }
  34814. else {
  34815. this.stop(0);
  34816. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34817. }
  34818. }
  34819. };
  34820. Sound.prototype.setVolume = function (newVolume, time) {
  34821. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34822. if (time) {
  34823. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34824. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34825. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34826. }
  34827. else {
  34828. this._soundGain.gain.value = newVolume;
  34829. }
  34830. }
  34831. this._volume = newVolume;
  34832. };
  34833. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34834. this._playbackRate = newPlaybackRate;
  34835. if (this.isPlaying) {
  34836. if (this._streaming) {
  34837. this._htmlAudioElement.playbackRate = this._playbackRate;
  34838. }
  34839. else {
  34840. this._soundSource.playbackRate.value = this._playbackRate;
  34841. }
  34842. }
  34843. };
  34844. Sound.prototype.getVolume = function () {
  34845. return this._volume;
  34846. };
  34847. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34848. var _this = this;
  34849. if (this._connectedMesh) {
  34850. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34851. this._registerFunc = null;
  34852. }
  34853. this._connectedMesh = meshToConnectTo;
  34854. if (!this.spatialSound) {
  34855. this.spatialSound = true;
  34856. this._createSpatialParameters();
  34857. if (this.isPlaying && this.loop) {
  34858. this.stop();
  34859. this.play();
  34860. }
  34861. }
  34862. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34863. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34864. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34865. };
  34866. Sound.prototype.detachFromMesh = function () {
  34867. if (this._connectedMesh) {
  34868. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34869. this._registerFunc = null;
  34870. this._connectedMesh = null;
  34871. }
  34872. };
  34873. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34874. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34875. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34876. this._updateDirection();
  34877. }
  34878. };
  34879. Sound.prototype.clone = function () {
  34880. var _this = this;
  34881. if (!this._streaming) {
  34882. var setBufferAndRun = function () {
  34883. if (_this._isReadyToPlay) {
  34884. clonedSound._audioBuffer = _this.getAudioBuffer();
  34885. clonedSound._isReadyToPlay = true;
  34886. if (clonedSound.autoplay) {
  34887. clonedSound.play();
  34888. }
  34889. }
  34890. else {
  34891. window.setTimeout(setBufferAndRun, 300);
  34892. }
  34893. };
  34894. var currentOptions = {
  34895. autoplay: this.autoplay, loop: this.loop,
  34896. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34897. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34898. refDistance: this.refDistance, distanceModel: this.distanceModel
  34899. };
  34900. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34901. if (this.useCustomAttenuation) {
  34902. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34903. }
  34904. clonedSound.setPosition(this._position);
  34905. clonedSound.setPlaybackRate(this._playbackRate);
  34906. setBufferAndRun();
  34907. return clonedSound;
  34908. }
  34909. else {
  34910. return null;
  34911. }
  34912. };
  34913. Sound.prototype.getAudioBuffer = function () {
  34914. return this._audioBuffer;
  34915. };
  34916. Sound.prototype.serialize = function () {
  34917. var serializationObject = {
  34918. name: this.name,
  34919. url: this.name,
  34920. autoplay: this.autoplay,
  34921. loop: this.loop,
  34922. volume: this._volume,
  34923. spatialSound: this.spatialSound,
  34924. maxDistance: this.maxDistance,
  34925. rolloffFactor: this.rolloffFactor,
  34926. refDistance: this.refDistance,
  34927. distanceModel: this.distanceModel,
  34928. playbackRate: this._playbackRate,
  34929. panningModel: this._panningModel,
  34930. soundTrackId: this.soundTrackId
  34931. };
  34932. if (this.spatialSound) {
  34933. if (this._connectedMesh)
  34934. serializationObject.connectedMeshId = this._connectedMesh.id;
  34935. serializationObject.position = this._position.asArray();
  34936. serializationObject.refDistance = this.refDistance;
  34937. serializationObject.distanceModel = this.distanceModel;
  34938. serializationObject.isDirectional = this._isDirectional;
  34939. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  34940. serializationObject.coneInnerAngle = this._coneInnerAngle;
  34941. serializationObject.coneOuterAngle = this._coneOuterAngle;
  34942. serializationObject.coneOuterGain = this._coneOuterGain;
  34943. }
  34944. return serializationObject;
  34945. };
  34946. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34947. var soundName = parsedSound.name;
  34948. var soundUrl;
  34949. if (parsedSound.url) {
  34950. soundUrl = rootUrl + parsedSound.url;
  34951. }
  34952. else {
  34953. soundUrl = rootUrl + soundName;
  34954. }
  34955. var options = {
  34956. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34957. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34958. rolloffFactor: parsedSound.rolloffFactor,
  34959. refDistance: parsedSound.refDistance,
  34960. distanceModel: parsedSound.distanceModel,
  34961. playbackRate: parsedSound.playbackRate
  34962. };
  34963. var newSound;
  34964. if (!sourceSound) {
  34965. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34966. scene._addPendingData(newSound);
  34967. }
  34968. else {
  34969. var setBufferAndRun = function () {
  34970. if (sourceSound._isReadyToPlay) {
  34971. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34972. newSound._isReadyToPlay = true;
  34973. if (newSound.autoplay) {
  34974. newSound.play();
  34975. }
  34976. }
  34977. else {
  34978. window.setTimeout(setBufferAndRun, 300);
  34979. }
  34980. };
  34981. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34982. setBufferAndRun();
  34983. }
  34984. if (parsedSound.position) {
  34985. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34986. newSound.setPosition(soundPosition);
  34987. }
  34988. if (parsedSound.isDirectional) {
  34989. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34990. if (parsedSound.localDirectionToMesh) {
  34991. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34992. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34993. }
  34994. }
  34995. if (parsedSound.connectedMeshId) {
  34996. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34997. if (connectedMesh) {
  34998. newSound.attachToMesh(connectedMesh);
  34999. }
  35000. }
  35001. return newSound;
  35002. };
  35003. return Sound;
  35004. })();
  35005. BABYLON.Sound = Sound;
  35006. })(BABYLON || (BABYLON = {}));
  35007. var BABYLON;
  35008. (function (BABYLON) {
  35009. var SoundTrack = (function () {
  35010. function SoundTrack(scene, options) {
  35011. this.id = -1;
  35012. this._isMainTrack = false;
  35013. this._isInitialized = false;
  35014. this._scene = scene;
  35015. this.soundCollection = new Array();
  35016. this._options = options;
  35017. if (!this._isMainTrack) {
  35018. this._scene.soundTracks.push(this);
  35019. this.id = this._scene.soundTracks.length - 1;
  35020. }
  35021. }
  35022. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35023. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35024. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35025. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35026. if (this._options) {
  35027. if (this._options.volume) {
  35028. this._outputAudioNode.gain.value = this._options.volume;
  35029. }
  35030. if (this._options.mainTrack) {
  35031. this._isMainTrack = this._options.mainTrack;
  35032. }
  35033. }
  35034. this._isInitialized = true;
  35035. }
  35036. };
  35037. SoundTrack.prototype.dispose = function () {
  35038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35039. if (this._connectedAnalyser) {
  35040. this._connectedAnalyser.stopDebugCanvas();
  35041. }
  35042. while (this.soundCollection.length) {
  35043. this.soundCollection[0].dispose();
  35044. }
  35045. if (this._outputAudioNode) {
  35046. this._outputAudioNode.disconnect();
  35047. }
  35048. this._outputAudioNode = null;
  35049. }
  35050. };
  35051. SoundTrack.prototype.AddSound = function (sound) {
  35052. if (!this._isInitialized) {
  35053. this._initializeSoundTrackAudioGraph();
  35054. }
  35055. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35056. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35057. }
  35058. if (sound.soundTrackId) {
  35059. if (sound.soundTrackId === -1) {
  35060. this._scene.mainSoundTrack.RemoveSound(sound);
  35061. }
  35062. else {
  35063. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35064. }
  35065. }
  35066. this.soundCollection.push(sound);
  35067. sound.soundTrackId = this.id;
  35068. };
  35069. SoundTrack.prototype.RemoveSound = function (sound) {
  35070. var index = this.soundCollection.indexOf(sound);
  35071. if (index !== -1) {
  35072. this.soundCollection.splice(index, 1);
  35073. }
  35074. };
  35075. SoundTrack.prototype.setVolume = function (newVolume) {
  35076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35077. this._outputAudioNode.gain.value = newVolume;
  35078. }
  35079. };
  35080. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35081. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35082. for (var i = 0; i < this.soundCollection.length; i++) {
  35083. this.soundCollection[i].switchPanningModelToHRTF();
  35084. }
  35085. }
  35086. };
  35087. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35088. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35089. for (var i = 0; i < this.soundCollection.length; i++) {
  35090. this.soundCollection[i].switchPanningModelToEqualPower();
  35091. }
  35092. }
  35093. };
  35094. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35095. if (this._connectedAnalyser) {
  35096. this._connectedAnalyser.stopDebugCanvas();
  35097. }
  35098. this._connectedAnalyser = analyser;
  35099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35100. this._outputAudioNode.disconnect();
  35101. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35102. }
  35103. };
  35104. return SoundTrack;
  35105. })();
  35106. BABYLON.SoundTrack = SoundTrack;
  35107. })(BABYLON || (BABYLON = {}));
  35108. var BABYLON;
  35109. (function (BABYLON) {
  35110. var SIMDVector3 = (function () {
  35111. function SIMDVector3() {
  35112. }
  35113. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  35114. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  35115. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35116. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35117. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35118. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35119. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  35120. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35121. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35122. };
  35123. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  35124. var v0 = SIMD.float32x4.splat(x);
  35125. var v1 = SIMD.float32x4.splat(y);
  35126. var v2 = SIMD.float32x4.splat(z);
  35127. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35128. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35129. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35130. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35131. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  35132. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35133. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35134. };
  35135. return SIMDVector3;
  35136. })();
  35137. BABYLON.SIMDVector3 = SIMDVector3;
  35138. var SIMDMatrix = (function () {
  35139. function SIMDMatrix() {
  35140. }
  35141. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  35142. if (offset === void 0) { offset = 0; }
  35143. var tm = this.m;
  35144. var om = other.m;
  35145. var om0 = SIMD.float32x4.load(om, 0);
  35146. var om1 = SIMD.float32x4.load(om, 4);
  35147. var om2 = SIMD.float32x4.load(om, 8);
  35148. var om3 = SIMD.float32x4.load(om, 12);
  35149. var tm0 = SIMD.float32x4.load(tm, 0);
  35150. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  35151. var tm1 = SIMD.float32x4.load(tm, 4);
  35152. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  35153. var tm2 = SIMD.float32x4.load(tm, 8);
  35154. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  35155. var tm3 = SIMD.float32x4.load(tm, 12);
  35156. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  35157. };
  35158. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  35159. var src = this.m;
  35160. var dest = other.m;
  35161. var row0, row1, row2, row3;
  35162. var tmp1;
  35163. var minor0, minor1, minor2, minor3;
  35164. var det;
  35165. // Load the 4 rows
  35166. var src0 = SIMD.float32x4.load(src, 0);
  35167. var src1 = SIMD.float32x4.load(src, 4);
  35168. var src2 = SIMD.float32x4.load(src, 8);
  35169. var src3 = SIMD.float32x4.load(src, 12);
  35170. // Transpose the source matrix. Sort of. Not a true transpose operation
  35171. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35172. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35173. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  35174. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  35175. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35176. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35177. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  35178. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  35179. // This is a true transposition, but it will lead to an incorrect result
  35180. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35181. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35182. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35183. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35184. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35185. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35186. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35187. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35188. // ----
  35189. tmp1 = SIMD.float32x4.mul(row2, row3);
  35190. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35191. minor0 = SIMD.float32x4.mul(row1, tmp1);
  35192. minor1 = SIMD.float32x4.mul(row0, tmp1);
  35193. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35194. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  35195. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  35196. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  35197. // ----
  35198. tmp1 = SIMD.float32x4.mul(row1, row2);
  35199. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35200. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  35201. minor3 = SIMD.float32x4.mul(row0, tmp1);
  35202. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35203. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  35204. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  35205. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  35206. // ----
  35207. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  35208. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35209. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  35210. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  35211. minor2 = SIMD.float32x4.mul(row0, tmp1);
  35212. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35213. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  35214. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  35215. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  35216. // ----
  35217. tmp1 = SIMD.float32x4.mul(row0, row1);
  35218. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35219. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  35220. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  35221. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35222. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  35223. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  35224. // ----
  35225. tmp1 = SIMD.float32x4.mul(row0, row3);
  35226. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35227. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  35228. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  35229. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35230. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  35231. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  35232. // ----
  35233. tmp1 = SIMD.float32x4.mul(row0, row2);
  35234. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35235. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  35236. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  35237. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35238. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  35239. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  35240. // Compute determinant
  35241. det = SIMD.float32x4.mul(row0, minor0);
  35242. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  35243. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  35244. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  35245. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  35246. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  35247. // These shuffles aren't necessary if the faulty transposition is done
  35248. // up at the top of this function.
  35249. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  35250. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  35251. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  35252. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  35253. // Compute final values by multiplying with 1/det
  35254. minor0 = SIMD.float32x4.mul(det, minor0);
  35255. minor1 = SIMD.float32x4.mul(det, minor1);
  35256. minor2 = SIMD.float32x4.mul(det, minor2);
  35257. minor3 = SIMD.float32x4.mul(det, minor3);
  35258. SIMD.float32x4.store(dest, 0, minor0);
  35259. SIMD.float32x4.store(dest, 4, minor1);
  35260. SIMD.float32x4.store(dest, 8, minor2);
  35261. SIMD.float32x4.store(dest, 12, minor3);
  35262. return this;
  35263. };
  35264. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  35265. var out = result.m;
  35266. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  35267. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  35268. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  35269. // cc.kmVec3Subtract(f, pCenter, pEye);
  35270. var f = SIMD.float32x4.sub(center, eye);
  35271. // cc.kmVec3Normalize(f, f);
  35272. var tmp = SIMD.float32x4.mul(f, f);
  35273. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35274. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35275. // cc.kmVec3Assign(up, pUp);
  35276. // cc.kmVec3Normalize(up, up);
  35277. tmp = SIMD.float32x4.mul(up, up);
  35278. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35279. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35280. // cc.kmVec3Cross(s, f, up);
  35281. 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)));
  35282. // cc.kmVec3Normalize(s, s);
  35283. tmp = SIMD.float32x4.mul(s, s);
  35284. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35285. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35286. // cc.kmVec3Cross(u, s, f);
  35287. 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)));
  35288. // cc.kmVec3Normalize(s, s);
  35289. tmp = SIMD.float32x4.mul(s, s);
  35290. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35291. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35292. var zero = SIMD.float32x4.splat(0.0);
  35293. s = SIMD.float32x4.neg(s);
  35294. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  35295. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  35296. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35297. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  35298. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  35299. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  35300. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35301. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  35302. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  35303. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  35304. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  35305. var b3 = SIMD.float32x4.neg(eye);
  35306. b3 = SIMD.float32x4.withW(b3, 1.0);
  35307. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  35308. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  35309. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  35310. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  35311. };
  35312. return SIMDMatrix;
  35313. })();
  35314. BABYLON.SIMDMatrix = SIMDMatrix;
  35315. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  35316. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  35317. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  35318. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  35319. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  35320. var SIMDHelper = (function () {
  35321. function SIMDHelper() {
  35322. }
  35323. Object.defineProperty(SIMDHelper, "IsEnabled", {
  35324. get: function () {
  35325. return SIMDHelper._isEnabled;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. SIMDHelper.DisableSIMD = function () {
  35331. // Replace functions
  35332. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  35333. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  35334. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  35335. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  35336. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  35337. SIMDHelper._isEnabled = false;
  35338. };
  35339. SIMDHelper.EnableSIMD = function () {
  35340. if (window.SIMD === undefined) {
  35341. return;
  35342. }
  35343. // Replace functions
  35344. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  35345. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  35346. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  35347. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  35348. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  35349. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  35350. get: function () { return this._data[0]; },
  35351. set: function (value) {
  35352. if (!this._data) {
  35353. this._data = new Float32Array(3);
  35354. }
  35355. this._data[0] = value;
  35356. }
  35357. });
  35358. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  35359. get: function () { return this._data[1]; },
  35360. set: function (value) {
  35361. this._data[1] = value;
  35362. }
  35363. });
  35364. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  35365. get: function () { return this._data[2]; },
  35366. set: function (value) {
  35367. this._data[2] = value;
  35368. }
  35369. });
  35370. SIMDHelper._isEnabled = true;
  35371. };
  35372. SIMDHelper._isEnabled = false;
  35373. return SIMDHelper;
  35374. })();
  35375. BABYLON.SIMDHelper = SIMDHelper;
  35376. })(BABYLON || (BABYLON = {}));
  35377. var BABYLON;
  35378. (function (BABYLON) {
  35379. /**
  35380. * This class describe a rectangle that were added to the map.
  35381. * You have access to its coordinates either in pixel or normalized (UV)
  35382. */
  35383. var PackedRect = (function () {
  35384. function PackedRect(root, parent, pos, size) {
  35385. this._pos = pos;
  35386. this._size = size;
  35387. this._root = root;
  35388. this._parent = parent;
  35389. }
  35390. Object.defineProperty(PackedRect.prototype, "pos", {
  35391. /**
  35392. * @returns the position of this node into the map
  35393. */
  35394. get: function () {
  35395. return this._pos;
  35396. },
  35397. enumerable: true,
  35398. configurable: true
  35399. });
  35400. Object.defineProperty(PackedRect.prototype, "contentSize", {
  35401. /**
  35402. * @returns the size of the rectangle this node handles
  35403. */
  35404. get: function () {
  35405. return this._contentSize;
  35406. },
  35407. enumerable: true,
  35408. configurable: true
  35409. });
  35410. Object.defineProperty(PackedRect.prototype, "UVs", {
  35411. /**
  35412. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  35413. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  35414. */
  35415. get: function () {
  35416. return this.getUVsForCustomSize(this._root._size);
  35417. },
  35418. enumerable: true,
  35419. configurable: true
  35420. });
  35421. /**
  35422. * 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.
  35423. * This method will return the UVs for this part by given the custom size of what you really use
  35424. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  35425. */
  35426. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  35427. var mainWidth = this._root._size.width;
  35428. var mainHeight = this._root._size.height;
  35429. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  35430. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  35431. var uvs = new Array();
  35432. uvs.push(topLeft);
  35433. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  35434. uvs.push(rightBottom);
  35435. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  35436. return uvs;
  35437. };
  35438. /**
  35439. * Free this rectangle from the map.
  35440. * Call this method when you no longer need the rectangle to be in the map.
  35441. */
  35442. PackedRect.prototype.freeContent = function () {
  35443. if (!this.contentSize) {
  35444. return;
  35445. }
  35446. this._contentSize = null;
  35447. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  35448. this.attemptDefrag();
  35449. };
  35450. Object.defineProperty(PackedRect.prototype, "isUsed", {
  35451. get: function () {
  35452. return this._contentSize != null || this._leftNode != null;
  35453. },
  35454. enumerable: true,
  35455. configurable: true
  35456. });
  35457. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  35458. var node = this.findNode(contentSize);
  35459. // Not enough space...
  35460. if (!node) {
  35461. return null;
  35462. }
  35463. node.splitNode(contentSize);
  35464. return node;
  35465. };
  35466. PackedRect.prototype.findNode = function (size) {
  35467. var resNode = null;
  35468. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35469. if (this.isUsed) {
  35470. if (this._leftNode) {
  35471. resNode = this._leftNode.findNode(size);
  35472. }
  35473. if (!resNode && this._rightNode) {
  35474. resNode = this._rightNode.findNode(size);
  35475. }
  35476. if (!resNode && this._bottomNode) {
  35477. resNode = this._bottomNode.findNode(size);
  35478. }
  35479. }
  35480. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35481. resNode = this;
  35482. }
  35483. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35484. resNode = this;
  35485. }
  35486. return resNode;
  35487. };
  35488. PackedRect.prototype.splitNode = function (contentSize) {
  35489. // 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)
  35490. if (!this._contentSize && this._initialSize) {
  35491. 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));
  35492. return this._leftNode.splitNode(contentSize);
  35493. }
  35494. else {
  35495. this._contentSize = contentSize.clone();
  35496. this._initialSize = contentSize.clone();
  35497. if (contentSize.width !== this._size.width) {
  35498. 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));
  35499. }
  35500. if (contentSize.height !== this._size.height) {
  35501. 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));
  35502. }
  35503. return this;
  35504. }
  35505. };
  35506. PackedRect.prototype.attemptDefrag = function () {
  35507. if (!this.isUsed && this.isRecursiveFree) {
  35508. this.clearNode();
  35509. if (this._parent) {
  35510. this._parent.attemptDefrag();
  35511. }
  35512. }
  35513. };
  35514. PackedRect.prototype.clearNode = function () {
  35515. this._initialSize = null;
  35516. this._rightNode = null;
  35517. this._bottomNode = null;
  35518. };
  35519. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35520. get: function () {
  35521. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35522. },
  35523. enumerable: true,
  35524. configurable: true
  35525. });
  35526. PackedRect.prototype.evalFreeSize = function (size) {
  35527. var levelSize = 0;
  35528. if (!this.isUsed) {
  35529. if (this._initialSize) {
  35530. levelSize = this._initialSize.surface;
  35531. }
  35532. else {
  35533. levelSize = this._size.surface;
  35534. }
  35535. }
  35536. if (this._rightNode) {
  35537. levelSize += this._rightNode.evalFreeSize(0);
  35538. }
  35539. if (this._bottomNode) {
  35540. levelSize += this._bottomNode.evalFreeSize(0);
  35541. }
  35542. return levelSize + size;
  35543. };
  35544. return PackedRect;
  35545. })();
  35546. BABYLON.PackedRect = PackedRect;
  35547. /**
  35548. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35549. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35550. * 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.
  35551. */
  35552. var RectPackingMap = (function (_super) {
  35553. __extends(RectPackingMap, _super);
  35554. /**
  35555. * Create an instance of the object with a dimension using the given size
  35556. * @param size The dimension of the rectangle that will contain all the sub ones.
  35557. */
  35558. function RectPackingMap(size) {
  35559. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35560. this._root = this;
  35561. }
  35562. /**
  35563. * Add a rectangle, finding the best location to store it into the map
  35564. * @param size the dimension of the rectangle to store
  35565. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35566. */
  35567. RectPackingMap.prototype.addRect = function (size) {
  35568. var node = this.findAndSplitNode(size);
  35569. return node;
  35570. };
  35571. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35572. /**
  35573. * Return the current space free normalized between [0;1]
  35574. * @returns {}
  35575. */
  35576. get: function () {
  35577. var freeSize = 0;
  35578. freeSize = this.evalFreeSize(freeSize);
  35579. return freeSize / (this._size.width * this._size.height);
  35580. },
  35581. enumerable: true,
  35582. configurable: true
  35583. });
  35584. return RectPackingMap;
  35585. })(PackedRect);
  35586. BABYLON.RectPackingMap = RectPackingMap;
  35587. })(BABYLON || (BABYLON = {}));
  35588. var BABYLON;
  35589. (function (BABYLON) {
  35590. var DynamicFloatArrayElementInfo = (function () {
  35591. function DynamicFloatArrayElementInfo() {
  35592. }
  35593. return DynamicFloatArrayElementInfo;
  35594. })();
  35595. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35596. /**
  35597. * 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.
  35598. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35599. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35600. * 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.
  35601. * 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.
  35602. * 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".
  35603. */
  35604. var DynamicFloatArray = (function () {
  35605. /**
  35606. * Construct an instance of the dynamic float array
  35607. * @param stride size of one element in float (i.e. not bytes!)
  35608. * @param initialElementCount the number of available entries at construction
  35609. */
  35610. function DynamicFloatArray(stride, initialElementCount) {
  35611. this.compareValueOffset = null;
  35612. this.sortingAscending = true;
  35613. this._stride = stride;
  35614. this.buffer = new Float32Array(stride * initialElementCount);
  35615. this._lastUsed = 0;
  35616. this._firstFree = 0;
  35617. this._allEntries = new Array(initialElementCount);
  35618. this._freeEntries = new Array(initialElementCount);
  35619. for (var i = 0; i < initialElementCount; i++) {
  35620. var element = new DynamicFloatArrayElementInfo();
  35621. element.offset = i * stride;
  35622. this._allEntries[i] = element;
  35623. this._freeEntries[initialElementCount - i - 1] = element;
  35624. }
  35625. }
  35626. /**
  35627. * Allocate an element in the array.
  35628. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35629. * Beware, this offset may change when you call pack()
  35630. */
  35631. DynamicFloatArray.prototype.allocElement = function () {
  35632. if (this._freeEntries.length === 0) {
  35633. this._growBuffer();
  35634. }
  35635. var el = this._freeEntries.pop();
  35636. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35637. if (el.offset === this._firstFree) {
  35638. if (this._freeEntries.length > 0) {
  35639. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35640. }
  35641. else {
  35642. this._firstFree += this._stride;
  35643. }
  35644. }
  35645. return el;
  35646. };
  35647. /**
  35648. * Free the element corresponding to the given element info
  35649. * @param elInfo the element that describe the allocated element
  35650. */
  35651. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35652. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35653. this._freeEntries.push(elInfo);
  35654. };
  35655. /**
  35656. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35657. * 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().
  35658. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35659. */
  35660. DynamicFloatArray.prototype.pack = function () {
  35661. // no free slot? no need to pack
  35662. if (this._freeEntries.length === 0) {
  35663. return this.buffer;
  35664. }
  35665. // If the buffer is already packed the last used will always be lower than the first free
  35666. // 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.
  35667. if (this._lastUsed < this._firstFree) {
  35668. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35669. return elementsBuffer_1;
  35670. }
  35671. var s = this._stride;
  35672. // 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
  35673. var lastFree = new DynamicFloatArrayElementInfo();
  35674. lastFree.offset = this.totalElementCount * s;
  35675. this._freeEntries.push(lastFree);
  35676. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35677. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35678. var firstFreeSlotOffset = sortedFree[0].offset;
  35679. var freeZoneSize = 1;
  35680. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35681. var prevOffset = sortedFree[0].offset;
  35682. for (var i = 1; i < sortedFree.length; i++) {
  35683. // 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
  35684. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35685. break;
  35686. }
  35687. var curFree = sortedFree[i];
  35688. var curOffset = curFree.offset;
  35689. // Compute the distance between this offset and the previous
  35690. var distance = curOffset - prevOffset;
  35691. // If the distance is the stride size, they are adjacent, it good, move to the next
  35692. if (distance === s) {
  35693. // Free zone is one element bigger
  35694. ++freeZoneSize;
  35695. // as we're about to iterate to the next, the cur becomes the previous...
  35696. prevOffset = curOffset;
  35697. continue;
  35698. }
  35699. // Distance is bigger, which means there's x element between the previous free and this one
  35700. var usedRange = (distance / s) - 1;
  35701. // Two cases the free zone is smaller than the data to move or bigger
  35702. // Copy what can fit in the free zone
  35703. var curMoveOffset = curOffset - s;
  35704. var copyCount = Math.min(freeZoneSize, usedRange);
  35705. for (var j = 0; j < copyCount; j++) {
  35706. var freeI = firstFreeSlotOffset / s;
  35707. var curI = curMoveOffset / s;
  35708. var moveEl = sortedAll[curI];
  35709. this._moveElement(moveEl, firstFreeSlotOffset);
  35710. var replacedEl = sortedAll[freeI];
  35711. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35712. replacedEl.offset = curMoveOffset;
  35713. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35714. sortedAll[freeI] = moveEl;
  35715. sortedAll[curI] = replacedEl;
  35716. curMoveOffset -= s;
  35717. firstFreeSlotOffset += s;
  35718. }
  35719. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35720. if (freeZoneSize <= usedRange) {
  35721. firstFreeSlotOffset = curMoveOffset + s;
  35722. freeZoneSize = 1 + copyCount;
  35723. }
  35724. else {
  35725. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35726. }
  35727. // as we're about to iterate to the next, the cur becomes the previous...
  35728. prevOffset = curOffset;
  35729. }
  35730. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35731. this._lastUsed = firstFreeSlotOffset - s;
  35732. this._firstFree = firstFreeSlotOffset;
  35733. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35734. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35735. this._allEntries = sortedAll;
  35736. return elementsBuffer;
  35737. };
  35738. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35739. for (var i = 0; i < this._stride; i++) {
  35740. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35741. }
  35742. element.offset = destOffset;
  35743. };
  35744. DynamicFloatArray.prototype._growBuffer = function () {
  35745. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35746. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35747. var newBuffer = new Float32Array(newElCount * this._stride);
  35748. newBuffer.set(this.buffer);
  35749. var curCount = this.totalElementCount;
  35750. var addedCount = newElCount - this.totalElementCount;
  35751. for (var i = 0; i < addedCount; i++) {
  35752. var element = new DynamicFloatArrayElementInfo();
  35753. element.offset = (curCount + i) * this.stride;
  35754. this._allEntries.push(element);
  35755. this._freeEntries[addedCount - i - 1] = element;
  35756. }
  35757. this._firstFree = curCount * this.stride;
  35758. this.buffer = newBuffer;
  35759. };
  35760. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35761. /**
  35762. * Get the total count of entries that can fit in the current buffer
  35763. * @returns the elements count
  35764. */
  35765. get: function () {
  35766. return this._allEntries.length;
  35767. },
  35768. enumerable: true,
  35769. configurable: true
  35770. });
  35771. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35772. /**
  35773. * Get the count of free entries that can still be allocated without resizing the buffer
  35774. * @returns the free elements count
  35775. */
  35776. get: function () {
  35777. return this._freeEntries.length;
  35778. },
  35779. enumerable: true,
  35780. configurable: true
  35781. });
  35782. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  35783. /**
  35784. * Get the count of allocated elements
  35785. * @returns the allocated elements count
  35786. */
  35787. get: function () {
  35788. return this._allEntries.length - this._freeEntries.length;
  35789. },
  35790. enumerable: true,
  35791. configurable: true
  35792. });
  35793. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  35794. /**
  35795. * Return the size of one element in float
  35796. * @returns the size in float
  35797. */
  35798. get: function () {
  35799. return this._stride;
  35800. },
  35801. enumerable: true,
  35802. configurable: true
  35803. });
  35804. DynamicFloatArray.prototype.sort = function () {
  35805. var _this = this;
  35806. if (!this.compareValueOffset) {
  35807. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  35808. }
  35809. var count = this.usedElementCount;
  35810. // Do we have to (re)create the sort table?
  35811. if (!this._sortTable || this._sortTable.length < count) {
  35812. // 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...
  35813. var newCount = Math.min(this.totalElementCount, count * 2);
  35814. this._sortTable = new Array(newCount);
  35815. }
  35816. if (!this._sortTable || this._sortTable.length !== count) {
  35817. this._sortedTable = new Array(count);
  35818. }
  35819. // Because, you know...
  35820. this.pack();
  35821. //let stride = this.stride;
  35822. //for (let i = 0; i < count; i++) {
  35823. // let si = this._sortTable[i];
  35824. // if (!si) {
  35825. // si = new SortInfo();
  35826. // this._sortTable[i] = si;
  35827. // }
  35828. // si.entry = this._allEntries[i];
  35829. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  35830. // si.swapedOffset = null;
  35831. // this._sortedTable[i] = si;
  35832. //}
  35833. var curOffset = 0;
  35834. var stride = this.stride;
  35835. for (var i = 0; i < count; i++, curOffset += stride) {
  35836. var si = this._sortTable[i];
  35837. if (!si) {
  35838. si = new SortInfo();
  35839. this._sortTable[i] = si;
  35840. }
  35841. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  35842. si.offset = curOffset;
  35843. si.swapedOffset = null;
  35844. this._sortedTable[i] = si;
  35845. }
  35846. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  35847. if (this.sortingAscending) {
  35848. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  35849. }
  35850. else {
  35851. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  35852. }
  35853. var swapElements = function (src, dst) {
  35854. for (var i = 0; i < stride; i++) {
  35855. var tps = _this.buffer[dst + i];
  35856. _this.buffer[dst + i] = _this.buffer[src + i];
  35857. _this.buffer[src + i] = tps;
  35858. }
  35859. };
  35860. // 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:
  35861. // 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),
  35862. // and I still want something with a good algorithm complexity.
  35863. // 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,
  35864. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  35865. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  35866. // 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
  35867. // until we find a SortInfo object without a swapedOffset which means we got the right location
  35868. // 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
  35869. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  35870. for (var i = 0; i < count; i++) {
  35871. // Get the element to move
  35872. var sourceSI = this._sortedTable[i];
  35873. var destSI = this._sortTable[i];
  35874. var sourceOff = sourceSI.offset;
  35875. // If the source changed location, find the new one
  35876. if (sourceSI.swapedOffset) {
  35877. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  35878. var curSI = sourceSI;
  35879. while (curSI.swapedOffset) {
  35880. curSI = this._sortTable[curSI.swapedOffset / stride];
  35881. }
  35882. // Finally get the right location
  35883. sourceOff = curSI.offset;
  35884. }
  35885. // Tag the element being replaced with its new location
  35886. destSI.swapedOffset = sourceOff;
  35887. // Swap elements (only if needed)
  35888. if (sourceOff !== destSI.offset) {
  35889. swapElements(sourceOff, destSI.offset);
  35890. }
  35891. // Update the offset in the corresponding DFAE
  35892. //sourceSI.entry.offset = destSI.entry.offset;
  35893. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  35894. }
  35895. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35896. return true;
  35897. };
  35898. return DynamicFloatArray;
  35899. })();
  35900. BABYLON.DynamicFloatArray = DynamicFloatArray;
  35901. var SortInfo = (function () {
  35902. function SortInfo() {
  35903. this.compareData = this.offset = this.swapedOffset = null;
  35904. }
  35905. return SortInfo;
  35906. })();
  35907. })(BABYLON || (BABYLON = {}));
  35908. var BABYLON;
  35909. (function (BABYLON) {
  35910. /**
  35911. * This class given information about a given character.
  35912. */
  35913. var CharInfo = (function () {
  35914. function CharInfo() {
  35915. }
  35916. return CharInfo;
  35917. })();
  35918. BABYLON.CharInfo = CharInfo;
  35919. var FontTexture = (function (_super) {
  35920. __extends(FontTexture, _super);
  35921. /**
  35922. * Create a new instance of the FontTexture class
  35923. * @param name the name of the texture
  35924. * @param font the font to use, use the W3C CSS notation
  35925. * @param scene the scene that owns the texture
  35926. * @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
  35927. * @param samplingMode the texture sampling mode
  35928. * @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.
  35929. */
  35930. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  35931. if (maxCharCount === void 0) { maxCharCount = 200; }
  35932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35933. if (superSample === void 0) { superSample = false; }
  35934. _super.call(this, null, scene, true, false, samplingMode);
  35935. this._charInfos = {};
  35936. this._curCharCount = 0;
  35937. this._lastUpdateCharCount = -1;
  35938. this._usedCounter = 1;
  35939. this.name = name;
  35940. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35941. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35942. this._superSample = false;
  35943. if (superSample) {
  35944. var sfont = this.getSuperSampleFont(font);
  35945. if (sfont) {
  35946. this._superSample = true;
  35947. font = sfont;
  35948. }
  35949. }
  35950. // First canvas creation to determine the size of the texture to create
  35951. this._canvas = document.createElement("canvas");
  35952. this._context = this._canvas.getContext("2d");
  35953. this._context.font = font;
  35954. this._context.fillStyle = "white";
  35955. var res = this.getFontHeight(font);
  35956. this._lineHeightSuper = res.height;
  35957. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  35958. this._offset = res.offset - 1;
  35959. var maxCharWidth = this._context.measureText("W").width;
  35960. this._spaceWidthSuper = this._context.measureText(" ").width;
  35961. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  35962. // This is an approximate size, but should always be able to fit at least the maxCharCount
  35963. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  35964. var edge = Math.sqrt(totalEstSurface);
  35965. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  35966. // Create the texture that will store the font characters
  35967. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  35968. var textureSize = this.getSize();
  35969. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  35970. this._canvas = document.createElement("canvas");
  35971. this._canvas.width = textureSize.width;
  35972. this._canvas.height = textureSize.height;
  35973. this._context = this._canvas.getContext("2d");
  35974. this._context.textBaseline = "top";
  35975. this._context.font = font;
  35976. this._context.fillStyle = "white";
  35977. this._context.imageSmoothingEnabled = false;
  35978. this._currentFreePosition = BABYLON.Vector2.Zero();
  35979. // Add the basic ASCII based characters
  35980. for (var i = 0x20; i < 0x7F; i++) {
  35981. var c = String.fromCharCode(i);
  35982. this.getChar(c);
  35983. }
  35984. this.update();
  35985. }
  35986. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  35987. get: function () {
  35988. return this._superSample;
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  35994. get: function () {
  35995. return this._spaceWidth;
  35996. },
  35997. enumerable: true,
  35998. configurable: true
  35999. });
  36000. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36001. get: function () {
  36002. return this._lineHeight;
  36003. },
  36004. enumerable: true,
  36005. configurable: true
  36006. });
  36007. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36008. if (supersample === void 0) { supersample = false; }
  36009. var s = scene;
  36010. if (!s.__fontTextureCache__) {
  36011. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36012. }
  36013. var dic = s.__fontTextureCache__;
  36014. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36015. var ft = dic.get(lfn);
  36016. if (ft) {
  36017. ++ft._usedCounter;
  36018. return ft;
  36019. }
  36020. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36021. dic.add(lfn, ft);
  36022. return ft;
  36023. };
  36024. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36025. if (supersample === void 0) { supersample = false; }
  36026. var s = scene;
  36027. var dic = s.__fontTextureCache__;
  36028. if (!dic) {
  36029. return;
  36030. }
  36031. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36032. var font = dic.get(lfn);
  36033. if (--font._usedCounter === 0) {
  36034. dic.remove(lfn);
  36035. font.dispose();
  36036. }
  36037. };
  36038. /**
  36039. * Make sure the given char is present in the font map.
  36040. * @param char the character to get or add
  36041. * @return the CharInfo instance corresponding to the given character
  36042. */
  36043. FontTexture.prototype.getChar = function (char) {
  36044. if (char.length !== 1) {
  36045. return null;
  36046. }
  36047. var info = this._charInfos[char];
  36048. if (info) {
  36049. return info;
  36050. }
  36051. info = new CharInfo();
  36052. var measure = this._context.measureText(char);
  36053. var textureSize = this.getSize();
  36054. // we reached the end of the current line?
  36055. var width = Math.round(measure.width);
  36056. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  36057. var yMargin = xMargin;
  36058. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  36059. this._currentFreePosition.x = 0;
  36060. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  36061. // No more room?
  36062. if (this._currentFreePosition.y > textureSize.height) {
  36063. return this.getChar("!");
  36064. }
  36065. }
  36066. // Draw the character in the texture
  36067. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  36068. // Fill the CharInfo object
  36069. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  36070. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  36071. info.charWidth = this._superSample ? (width / 2) : width;
  36072. // Add the info structure
  36073. this._charInfos[char] = info;
  36074. this._curCharCount++;
  36075. // Set the next position
  36076. this._currentFreePosition.x += width + xMargin;
  36077. return info;
  36078. };
  36079. FontTexture.prototype.measureText = function (text, tabulationSize) {
  36080. if (tabulationSize === void 0) { tabulationSize = 4; }
  36081. var maxWidth = 0;
  36082. var curWidth = 0;
  36083. var lineCount = 1;
  36084. var charxpos = 0;
  36085. // Parse each char of the string
  36086. for (var _i = 0; _i < text.length; _i++) {
  36087. var char = text[_i];
  36088. // Next line feed?
  36089. if (char === "\n") {
  36090. maxWidth = Math.max(maxWidth, curWidth);
  36091. charxpos = 0;
  36092. curWidth = 0;
  36093. ++lineCount;
  36094. continue;
  36095. }
  36096. // Tabulation ?
  36097. if (char === "\t") {
  36098. var nextPos = charxpos + tabulationSize;
  36099. nextPos = nextPos - (nextPos % tabulationSize);
  36100. curWidth += (nextPos - charxpos) * this.spaceWidth;
  36101. charxpos = nextPos;
  36102. continue;
  36103. }
  36104. if (char < " ") {
  36105. continue;
  36106. }
  36107. curWidth += this.getChar(char).charWidth;
  36108. ++charxpos;
  36109. }
  36110. maxWidth = Math.max(maxWidth, curWidth);
  36111. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  36112. };
  36113. FontTexture.prototype.getSuperSampleFont = function (font) {
  36114. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  36115. 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*$/;
  36116. var res = font.toLocaleLowerCase().match(regex);
  36117. if (res == null) {
  36118. return null;
  36119. }
  36120. var size = parseInt(res[4]);
  36121. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  36122. var newFont = "";
  36123. for (var j = 1; j < res.length; j++) {
  36124. if (res[j] != null) {
  36125. newFont += res[j] + " ";
  36126. }
  36127. }
  36128. return newFont;
  36129. };
  36130. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  36131. FontTexture.prototype.getFontHeight = function (font) {
  36132. var fontDraw = document.createElement("canvas");
  36133. var ctx = fontDraw.getContext('2d');
  36134. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  36135. ctx.textBaseline = 'top';
  36136. ctx.fillStyle = 'white';
  36137. ctx.font = font;
  36138. ctx.fillText('jH|', 0, 0);
  36139. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  36140. var start = -1;
  36141. var end = -1;
  36142. for (var row = 0; row < fontDraw.height; row++) {
  36143. for (var column = 0; column < fontDraw.width; column++) {
  36144. var index = (row * fontDraw.width + column) * 4;
  36145. if (pixels[index] === 0) {
  36146. if (column === fontDraw.width - 1 && start !== -1) {
  36147. end = row;
  36148. row = fontDraw.height;
  36149. break;
  36150. }
  36151. continue;
  36152. }
  36153. else {
  36154. if (start === -1) {
  36155. start = row;
  36156. }
  36157. break;
  36158. }
  36159. }
  36160. }
  36161. return { height: (end - start) + 1, offset: start - 1 };
  36162. };
  36163. Object.defineProperty(FontTexture.prototype, "canRescale", {
  36164. get: function () {
  36165. return false;
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. FontTexture.prototype.getContext = function () {
  36171. return this._context;
  36172. };
  36173. /**
  36174. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  36175. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  36176. */
  36177. FontTexture.prototype.update = function () {
  36178. // Update only if there's new char added since the previous update
  36179. if (this._lastUpdateCharCount < this._curCharCount) {
  36180. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  36181. this._lastUpdateCharCount = this._curCharCount;
  36182. }
  36183. };
  36184. // cloning should be prohibited, there's no point to duplicate this texture at all
  36185. FontTexture.prototype.clone = function () {
  36186. return null;
  36187. };
  36188. return FontTexture;
  36189. })(BABYLON.Texture);
  36190. BABYLON.FontTexture = FontTexture;
  36191. })(BABYLON || (BABYLON = {}));
  36192. var BABYLON;
  36193. (function (BABYLON) {
  36194. var MapTexture = (function (_super) {
  36195. __extends(MapTexture, _super);
  36196. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  36197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36198. if (useMipMap === void 0) { useMipMap = false; }
  36199. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  36200. this.name = name;
  36201. this._size = size;
  36202. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36203. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36204. // Create the rectPackMap that will allocate portion of the texture
  36205. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  36206. // Create the texture that will store the content
  36207. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  36208. }
  36209. /**
  36210. * Allocate a rectangle of a given size in the texture map
  36211. * @param size the size of the rectangle to allocation
  36212. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  36213. */
  36214. MapTexture.prototype.allocateRect = function (size) {
  36215. return this._rectPackingMap.addRect(size);
  36216. };
  36217. /**
  36218. * Free a given rectangle from the texture map
  36219. * @param rectInfo the instance corresponding to the rect to free.
  36220. */
  36221. MapTexture.prototype.freeRect = function (rectInfo) {
  36222. if (rectInfo) {
  36223. rectInfo.freeContent();
  36224. }
  36225. };
  36226. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  36227. /**
  36228. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  36229. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  36230. * @returns {}
  36231. */
  36232. get: function () {
  36233. return this._rectPackingMap.freeSpace;
  36234. },
  36235. enumerable: true,
  36236. configurable: true
  36237. });
  36238. /**
  36239. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  36240. * 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.
  36241. * Don't forget to call unbindTexture when you're done rendering
  36242. * @param rect the zone to render to
  36243. * @param clear true to clear the portion's color/depth data
  36244. */
  36245. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  36246. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  36247. };
  36248. /**
  36249. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  36250. * 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.
  36251. * Don't forget to call unbindTexture when you're done rendering
  36252. * @param pos the position into the texture
  36253. * @param size the portion to fit the clip space to
  36254. * @param clear true to clear the portion's color/depth data
  36255. */
  36256. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  36257. var engine = this.getScene().getEngine();
  36258. engine.bindFramebuffer(this._texture);
  36259. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  36260. if (clear) {
  36261. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  36262. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  36263. }
  36264. };
  36265. /**
  36266. * Unbind the texture map from the rendering engine.
  36267. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  36268. * @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.
  36269. */
  36270. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  36271. // Dump ?
  36272. if (dumpForDebug) {
  36273. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  36274. }
  36275. var engine = this.getScene().getEngine();
  36276. if (this._replacedViewport) {
  36277. engine.setViewport(this._replacedViewport);
  36278. this._replacedViewport = null;
  36279. }
  36280. engine.unBindFramebuffer(this._texture);
  36281. };
  36282. Object.defineProperty(MapTexture.prototype, "canRescale", {
  36283. get: function () {
  36284. return false;
  36285. },
  36286. enumerable: true,
  36287. configurable: true
  36288. });
  36289. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  36290. // Anyway, there's not much point to use this method for this kind of texture I guess
  36291. MapTexture.prototype.clone = function () {
  36292. return null;
  36293. };
  36294. return MapTexture;
  36295. })(BABYLON.Texture);
  36296. BABYLON.MapTexture = MapTexture;
  36297. })(BABYLON || (BABYLON = {}));
  36298. var BABYLON;
  36299. (function (BABYLON) {
  36300. /**
  36301. * Stores 2D Bounding Information.
  36302. * This class handles a circle area and a bounding rectangle one.
  36303. */
  36304. var BoundingInfo2D = (function () {
  36305. function BoundingInfo2D() {
  36306. this.radius = 0;
  36307. this.center = BABYLON.Vector2.Zero();
  36308. this.extent = BABYLON.Vector2.Zero();
  36309. }
  36310. /**
  36311. * Create a BoundingInfo2D object from a given size
  36312. * @param size the size that will be used to set the extend, radius will be computed from it.
  36313. */
  36314. BoundingInfo2D.CreateFromSize = function (size) {
  36315. var r = new BoundingInfo2D();
  36316. BoundingInfo2D.CreateFromSizeToRef(size, r);
  36317. return r;
  36318. };
  36319. /**
  36320. * Create a BoundingInfo2D object from a given radius
  36321. * @param radius the radius to use, the extent will be computed from it.
  36322. */
  36323. BoundingInfo2D.CreateFromRadius = function (radius) {
  36324. var r = new BoundingInfo2D();
  36325. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  36326. return r;
  36327. };
  36328. /**
  36329. * Create a BoundingInfo2D object from a list of points.
  36330. * The resulted object will be the smallest bounding area that includes all the given points.
  36331. * @param points an array of points to compute the bounding object from.
  36332. */
  36333. BoundingInfo2D.CreateFromPoints = function (points) {
  36334. var r = new BoundingInfo2D();
  36335. BoundingInfo2D.CreateFromPointsToRef(points, r);
  36336. return r;
  36337. };
  36338. /**
  36339. * Update a BoundingInfo2D object using the given Size as input
  36340. * @param size the bounding data will be computed from this size.
  36341. * @param b must be a valid/allocated object, it will contain the result of the operation
  36342. */
  36343. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  36344. if (!size) {
  36345. size = BABYLON.Size.Zero();
  36346. }
  36347. b.center.x = +size.width / 2;
  36348. b.center.y = +size.height / 2;
  36349. b.extent.x = b.center.x;
  36350. b.extent.y = b.center.y;
  36351. b.radius = b.extent.length();
  36352. };
  36353. /**
  36354. * Update a BoundingInfo2D object using the given radius as input
  36355. * @param radius the bounding data will be computed from this radius
  36356. * @param b must be a valid/allocated object, it will contain the result of the operation
  36357. */
  36358. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  36359. b.center.x = b.center.y = 0;
  36360. var r = +radius;
  36361. b.extent.x = r;
  36362. b.extent.y = r;
  36363. b.radius = r;
  36364. };
  36365. /**
  36366. * Update a BoundingInfo2D object using the given points array as input
  36367. * @param points the point array to use to update the bounding data
  36368. * @param b must be a valid/allocated object, it will contain the result of the operation
  36369. */
  36370. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  36371. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  36372. for (var _i = 0; _i < points.length; _i++) {
  36373. var p = points[_i];
  36374. xmin = Math.min(p.x, xmin);
  36375. xmax = Math.max(p.x, xmax);
  36376. ymin = Math.min(p.y, ymin);
  36377. ymax = Math.max(p.y, ymax);
  36378. }
  36379. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  36380. };
  36381. /**
  36382. * Update a BoundingInfo2D object using the given min/max values as input
  36383. * @param xmin the smallest x coordinate
  36384. * @param xmax the biggest x coordinate
  36385. * @param ymin the smallest y coordinate
  36386. * @param ymax the buggest y coordinate
  36387. * @param b must be a valid/allocated object, it will contain the result of the operation
  36388. */
  36389. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  36390. var w = xmax - xmin;
  36391. var h = ymax - ymin;
  36392. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  36393. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  36394. b.radius = b.extent.length();
  36395. };
  36396. /**
  36397. * Duplicate this instance and return a new one
  36398. * @return the duplicated instance
  36399. */
  36400. BoundingInfo2D.prototype.clone = function () {
  36401. var r = new BoundingInfo2D();
  36402. r.center = this.center.clone();
  36403. r.radius = this.radius;
  36404. r.extent = this.extent.clone();
  36405. return r;
  36406. };
  36407. /**
  36408. * return the max extend of the bounding info
  36409. */
  36410. BoundingInfo2D.prototype.max = function () {
  36411. var r = BABYLON.Vector2.Zero();
  36412. this.maxToRef(r);
  36413. return r;
  36414. };
  36415. /**
  36416. * Update a vector2 with the max extend of the bounding info
  36417. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  36418. */
  36419. BoundingInfo2D.prototype.maxToRef = function (result) {
  36420. result.x = this.center.x + this.extent.x;
  36421. result.y = this.center.y + this.extent.y;
  36422. };
  36423. /**
  36424. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  36425. * @param matrix the transformation matrix to apply
  36426. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  36427. */
  36428. BoundingInfo2D.prototype.transform = function (matrix) {
  36429. var r = new BoundingInfo2D();
  36430. this.transformToRef(matrix, r);
  36431. return r;
  36432. };
  36433. /**
  36434. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  36435. * @param other the second BoundingInfo2D to compute the union with this one
  36436. * @return a new instance containing the result of the union
  36437. */
  36438. BoundingInfo2D.prototype.union = function (other) {
  36439. var r = new BoundingInfo2D();
  36440. this.unionToRef(other, r);
  36441. return r;
  36442. };
  36443. /**
  36444. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  36445. * 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.
  36446. * @param matrix The matrix to use to compute the transformation
  36447. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  36448. */
  36449. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  36450. // Construct a bounding box based on the extent values
  36451. var p = BoundingInfo2D._transform;
  36452. p[0].x = this.center.x + this.extent.x;
  36453. p[0].y = this.center.y + this.extent.y;
  36454. p[1].x = this.center.x + this.extent.x;
  36455. p[1].y = this.center.y - this.extent.y;
  36456. p[2].x = this.center.x - this.extent.x;
  36457. p[2].y = this.center.y - this.extent.y;
  36458. p[3].x = this.center.x - this.extent.x;
  36459. p[3].y = this.center.y + this.extent.y;
  36460. // Transform the four points of the bounding box with the matrix
  36461. for (var i = 0; i < 4; i++) {
  36462. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  36463. }
  36464. BoundingInfo2D.CreateFromPointsToRef(p, result);
  36465. };
  36466. /**
  36467. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  36468. * 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.
  36469. * @param other the second object used to compute the union
  36470. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  36471. */
  36472. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  36473. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  36474. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  36475. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  36476. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  36477. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  36478. };
  36479. /**
  36480. * Check if the given point is inside the BoundingInfo.
  36481. * The test is first made on the radius, then inside the rectangle described by the extent
  36482. * @param pickPosition the position to test
  36483. * @return true if the point is inside, false otherwise
  36484. */
  36485. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  36486. // is it inside the radius?
  36487. var pickLocal = pickPosition.subtract(this.center);
  36488. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  36489. // is it inside the rectangle?
  36490. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  36491. }
  36492. return false;
  36493. };
  36494. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  36495. return BoundingInfo2D;
  36496. })();
  36497. BABYLON.BoundingInfo2D = BoundingInfo2D;
  36498. })(BABYLON || (BABYLON = {}));
  36499. var BABYLON;
  36500. (function (BABYLON) {
  36501. /**
  36502. * Base class implementing the ILocable interface.
  36503. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36504. */
  36505. var LockableBase = (function () {
  36506. function LockableBase() {
  36507. }
  36508. LockableBase.prototype.isLocked = function () {
  36509. return this._isLocked;
  36510. };
  36511. LockableBase.prototype.lock = function () {
  36512. if (this._isLocked) {
  36513. return true;
  36514. }
  36515. this.onLock();
  36516. this._isLocked = true;
  36517. return false;
  36518. };
  36519. /**
  36520. * Protected handler that will be called when the instance is about to be locked.
  36521. */
  36522. LockableBase.prototype.onLock = function () {
  36523. };
  36524. return LockableBase;
  36525. })();
  36526. BABYLON.LockableBase = LockableBase;
  36527. var SolidColorBrush2D = (function (_super) {
  36528. __extends(SolidColorBrush2D, _super);
  36529. function SolidColorBrush2D(color, lock) {
  36530. if (lock === void 0) { lock = false; }
  36531. _super.call(this);
  36532. this._color = color;
  36533. if (lock) {
  36534. {
  36535. this.lock();
  36536. }
  36537. }
  36538. }
  36539. /**
  36540. * Return true if the brush is transparent, false if it's totally opaque
  36541. */
  36542. SolidColorBrush2D.prototype.isTransparent = function () {
  36543. return this._color && this._color.a < 1.0;
  36544. };
  36545. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36546. /**
  36547. * The color used by this instance to render
  36548. * @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.
  36549. */
  36550. get: function () {
  36551. return this._color;
  36552. },
  36553. set: function (value) {
  36554. if (this.isLocked()) {
  36555. return;
  36556. }
  36557. this._color = value;
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. /**
  36563. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36564. */
  36565. SolidColorBrush2D.prototype.toString = function () {
  36566. return this._color.toHexString();
  36567. };
  36568. SolidColorBrush2D = __decorate([
  36569. BABYLON.className("SolidColorBrush2D")
  36570. ], SolidColorBrush2D);
  36571. return SolidColorBrush2D;
  36572. })(LockableBase);
  36573. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36574. var GradientColorBrush2D = (function (_super) {
  36575. __extends(GradientColorBrush2D, _super);
  36576. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36577. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36578. if (rotation === void 0) { rotation = 0; }
  36579. if (scale === void 0) { scale = 1; }
  36580. if (lock === void 0) { lock = false; }
  36581. _super.call(this);
  36582. this._color1 = color1;
  36583. this._color2 = color2;
  36584. this._translation = translation;
  36585. this._rotation = rotation;
  36586. this._scale = scale;
  36587. if (lock) {
  36588. this.lock();
  36589. }
  36590. }
  36591. /**
  36592. * Return true if the brush is transparent, false if it's totally opaque
  36593. */
  36594. GradientColorBrush2D.prototype.isTransparent = function () {
  36595. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36596. };
  36597. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36598. /**
  36599. * First color, the blend will start from this color
  36600. */
  36601. get: function () {
  36602. return this._color1;
  36603. },
  36604. set: function (value) {
  36605. if (this.isLocked()) {
  36606. return;
  36607. }
  36608. this._color1 = value;
  36609. },
  36610. enumerable: true,
  36611. configurable: true
  36612. });
  36613. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36614. /**
  36615. * Second color, the blend will end to this color
  36616. */
  36617. get: function () {
  36618. return this._color2;
  36619. },
  36620. set: function (value) {
  36621. if (this.isLocked()) {
  36622. return;
  36623. }
  36624. this._color2 = value;
  36625. },
  36626. enumerable: true,
  36627. configurable: true
  36628. });
  36629. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36630. /**
  36631. * Translation vector to apply on the blend
  36632. * Default is [0;0]
  36633. */
  36634. get: function () {
  36635. return this._translation;
  36636. },
  36637. set: function (value) {
  36638. if (this.isLocked()) {
  36639. return;
  36640. }
  36641. this._translation = value;
  36642. },
  36643. enumerable: true,
  36644. configurable: true
  36645. });
  36646. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  36647. /**
  36648. * Rotation in radian to apply to the brush
  36649. * Default direction of the brush is vertical, you can change this using this property.
  36650. * Default is 0.
  36651. */
  36652. get: function () {
  36653. return this._rotation;
  36654. },
  36655. set: function (value) {
  36656. if (this.isLocked()) {
  36657. return;
  36658. }
  36659. this._rotation = value;
  36660. },
  36661. enumerable: true,
  36662. configurable: true
  36663. });
  36664. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  36665. /**
  36666. * Scale factor to apply to the gradient.
  36667. * Default is 1: no scale.
  36668. */
  36669. get: function () {
  36670. return this._scale;
  36671. },
  36672. set: function (value) {
  36673. if (this.isLocked()) {
  36674. return;
  36675. }
  36676. this._scale = value;
  36677. },
  36678. enumerable: true,
  36679. configurable: true
  36680. });
  36681. /**
  36682. * Return a string describing the brush
  36683. */
  36684. GradientColorBrush2D.prototype.toString = function () {
  36685. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  36686. };
  36687. /**
  36688. * Build a unique key string for the given parameters
  36689. */
  36690. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  36691. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  36692. };
  36693. GradientColorBrush2D = __decorate([
  36694. BABYLON.className("GradientColorBrush2D")
  36695. ], GradientColorBrush2D);
  36696. return GradientColorBrush2D;
  36697. })(LockableBase);
  36698. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  36699. })(BABYLON || (BABYLON = {}));
  36700. var BABYLON;
  36701. (function (BABYLON) {
  36702. var Prim2DClassInfo = (function () {
  36703. function Prim2DClassInfo() {
  36704. }
  36705. return Prim2DClassInfo;
  36706. })();
  36707. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  36708. var Prim2DPropInfo = (function () {
  36709. function Prim2DPropInfo() {
  36710. }
  36711. Prim2DPropInfo.PROPKIND_MODEL = 1;
  36712. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  36713. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  36714. return Prim2DPropInfo;
  36715. })();
  36716. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  36717. /**
  36718. * Custom type of the propertyChanged observable
  36719. */
  36720. var PropertyChangedInfo = (function () {
  36721. function PropertyChangedInfo() {
  36722. }
  36723. return PropertyChangedInfo;
  36724. })();
  36725. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  36726. var ClassTreeInfo = (function () {
  36727. function ClassTreeInfo(baseClass, type, classContentFactory) {
  36728. this._baseClass = baseClass;
  36729. this._type = type;
  36730. this._subClasses = new Array();
  36731. this._levelContent = new BABYLON.StringDictionary();
  36732. this._classContentFactory = classContentFactory;
  36733. }
  36734. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  36735. get: function () {
  36736. if (!this._classContent) {
  36737. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  36738. }
  36739. return this._classContent;
  36740. },
  36741. enumerable: true,
  36742. configurable: true
  36743. });
  36744. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  36745. get: function () {
  36746. return this._type;
  36747. },
  36748. enumerable: true,
  36749. configurable: true
  36750. });
  36751. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  36752. get: function () {
  36753. return this._levelContent;
  36754. },
  36755. enumerable: true,
  36756. configurable: true
  36757. });
  36758. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  36759. get: function () {
  36760. if (!this._fullContent) {
  36761. var dic = new BABYLON.StringDictionary();
  36762. var curLevel = this;
  36763. while (curLevel) {
  36764. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  36765. curLevel = curLevel._baseClass;
  36766. }
  36767. this._fullContent = dic;
  36768. }
  36769. return this._fullContent;
  36770. },
  36771. enumerable: true,
  36772. configurable: true
  36773. });
  36774. ClassTreeInfo.prototype.getLevelOf = function (type) {
  36775. // Are we already there?
  36776. if (type === this._type) {
  36777. return this;
  36778. }
  36779. var baseProto = Object.getPrototypeOf(type);
  36780. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  36781. if (!curProtoContent) {
  36782. this.getLevelOf(baseProto);
  36783. }
  36784. return this.getOrAddType(baseProto, type);
  36785. };
  36786. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  36787. // Are we at the level corresponding to the baseType?
  36788. // If so, get or add the level we're looking for
  36789. if (baseType === this._type) {
  36790. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  36791. var subType = _a[_i];
  36792. if (subType.type === type) {
  36793. return subType.node;
  36794. }
  36795. }
  36796. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  36797. var info = { type: type, node: node };
  36798. this._subClasses.push(info);
  36799. return info.node;
  36800. }
  36801. // Recurse down to keep looking for the node corresponding to the baseTypeName
  36802. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  36803. var subType = _c[_b];
  36804. var info = subType.node.getOrAddType(baseType, type);
  36805. if (info) {
  36806. return info;
  36807. }
  36808. }
  36809. return null;
  36810. };
  36811. ClassTreeInfo.get = function (type) {
  36812. var dic = type["__classTreeInfo"];
  36813. if (!dic) {
  36814. return null;
  36815. }
  36816. return dic.getLevelOf(type);
  36817. };
  36818. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  36819. var dic = type["__classTreeInfo"];
  36820. if (!dic) {
  36821. dic = new ClassTreeInfo(null, type, classContentFactory);
  36822. type["__classTreeInfo"] = dic;
  36823. }
  36824. return dic;
  36825. };
  36826. return ClassTreeInfo;
  36827. })();
  36828. BABYLON.ClassTreeInfo = ClassTreeInfo;
  36829. var SmartPropertyPrim = (function () {
  36830. function SmartPropertyPrim() {
  36831. this._flags = 0;
  36832. this._modelKey = null;
  36833. this._instanceDirtyFlags = 0;
  36834. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  36835. this.animations = new Array();
  36836. }
  36837. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  36838. /**
  36839. * Check if the object is disposed or not.
  36840. * @returns true if the object is dispose, false otherwise.
  36841. */
  36842. get: function () {
  36843. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  36844. },
  36845. enumerable: true,
  36846. configurable: true
  36847. });
  36848. /**
  36849. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  36850. * @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.
  36851. */
  36852. SmartPropertyPrim.prototype.dispose = function () {
  36853. if (this.isDisposed) {
  36854. return false;
  36855. }
  36856. // Don't set to null, it may upset somebody...
  36857. this.animations.splice(0);
  36858. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  36859. return true;
  36860. };
  36861. /**
  36862. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  36863. * Look at Sprite2D for more information
  36864. */
  36865. SmartPropertyPrim.prototype.getAnimatables = function () {
  36866. return new Array();
  36867. };
  36868. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  36869. /**
  36870. * Property giving the Model Key associated to the property.
  36871. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  36872. * @returns the model key string.
  36873. */
  36874. get: function () {
  36875. var _this = this;
  36876. // No need to compute it?
  36877. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  36878. return this._modelKey;
  36879. }
  36880. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  36881. var propDic = this.propDic;
  36882. propDic.forEach(function (k, v) {
  36883. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36884. var propVal = _this[v.name];
  36885. // 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
  36886. if (propVal && propVal.constructor === Array) {
  36887. var firstVal = propVal[0];
  36888. if (!firstVal) {
  36889. propVal = 0;
  36890. }
  36891. else {
  36892. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  36893. }
  36894. }
  36895. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  36896. }
  36897. });
  36898. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  36899. this._modelKey = modelKey;
  36900. return modelKey;
  36901. },
  36902. enumerable: true,
  36903. configurable: true
  36904. });
  36905. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  36906. /**
  36907. * States if the Primitive is dirty and should be rendered again next time.
  36908. * @returns true is dirty, false otherwise
  36909. */
  36910. get: function () {
  36911. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  36912. },
  36913. enumerable: true,
  36914. configurable: true
  36915. });
  36916. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  36917. /**
  36918. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  36919. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  36920. */
  36921. get: function () {
  36922. if (!this._propInfo) {
  36923. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  36924. if (!cti) {
  36925. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  36926. }
  36927. this._propInfo = cti.fullContent;
  36928. }
  36929. return this._propInfo;
  36930. },
  36931. enumerable: true,
  36932. configurable: true
  36933. });
  36934. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  36935. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  36936. var node = dic.getLevelOf(target);
  36937. var propInfo = node.levelContent.get(propId.toString());
  36938. if (propInfo) {
  36939. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  36940. }
  36941. // Create, setup and add the PropInfo object to our prop dictionary
  36942. propInfo = new Prim2DPropInfo();
  36943. propInfo.id = propId;
  36944. propInfo.flagId = Math.pow(2, propId);
  36945. propInfo.kind = kind;
  36946. propInfo.name = propName;
  36947. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  36948. propInfo.typeLevelCompare = typeLevelCompare;
  36949. node.levelContent.add(propName, propInfo);
  36950. return propInfo;
  36951. };
  36952. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  36953. // Nothing to nothing: nothing to do!
  36954. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  36955. return true;
  36956. }
  36957. // Check value unchanged
  36958. if ((curValue != null) && (newValue != null)) {
  36959. if (typeof (curValue.equals) == "function") {
  36960. if (curValue.equals(newValue)) {
  36961. return true;
  36962. }
  36963. }
  36964. else {
  36965. if (curValue === newValue) {
  36966. return true;
  36967. }
  36968. }
  36969. }
  36970. return false;
  36971. };
  36972. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  36973. if (this.isDisposed) {
  36974. return;
  36975. }
  36976. var i = propertyName.indexOf(".");
  36977. if (i !== -1) {
  36978. propertyName = propertyName.substr(0, i);
  36979. }
  36980. var propInfo = this.propDic.get(propertyName);
  36981. if (!propInfo) {
  36982. return;
  36983. }
  36984. var newValue = this[propertyName];
  36985. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  36986. };
  36987. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  36988. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  36989. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  36990. if (this instanceof BABYLON.Prim2DBase) {
  36991. var curprim = this;
  36992. while (curprim) {
  36993. curprim._boundingSize = null;
  36994. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  36995. if (curprim.isSizeAuto) {
  36996. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  36997. }
  36998. if (curprim instanceof BABYLON.Group2D) {
  36999. if (curprim.isRenderableGroup) {
  37000. break;
  37001. }
  37002. }
  37003. curprim = curprim.parent;
  37004. }
  37005. }
  37006. };
  37007. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37008. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37009. if (propInfo.dirtyBoundingInfo) {
  37010. this._boundingBoxDirty();
  37011. }
  37012. // Trigger property changed
  37013. var info = SmartPropertyPrim.propChangedInfo;
  37014. info.oldValue = curValue;
  37015. info.newValue = newValue;
  37016. info.propertyName = propName;
  37017. var propMask = propInfo.flagId;
  37018. this.propertyChanged.notifyObservers(info, propMask);
  37019. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37020. if (this instanceof BABYLON.Group2D) {
  37021. this.handleGroupChanged(propInfo);
  37022. }
  37023. // Check for parent layout dirty
  37024. if (this instanceof BABYLON.Prim2DBase) {
  37025. var p = this._parent;
  37026. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  37027. p._setLayoutDirty();
  37028. }
  37029. }
  37030. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  37031. var instanceDirty = false;
  37032. if (typeLevelCompare && curValue != null && newValue != null) {
  37033. var cvProto = curValue.__proto__;
  37034. var nvProto = newValue.__proto__;
  37035. instanceDirty = (cvProto === nvProto);
  37036. }
  37037. // Set the dirty flags
  37038. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  37039. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  37040. }
  37041. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  37042. this.onPrimitivePropertyDirty(propMask);
  37043. }
  37044. };
  37045. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  37046. if (!this.isDirty) {
  37047. this.onPrimBecomesDirty();
  37048. }
  37049. this._instanceDirtyFlags |= propFlagId;
  37050. };
  37051. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  37052. };
  37053. /**
  37054. * Check if a given set of properties are dirty or not.
  37055. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37056. * @return true if at least one property is dirty, false if none of them are.
  37057. */
  37058. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  37059. return (this._instanceDirtyFlags & flags) !== 0;
  37060. };
  37061. /**
  37062. * Clear a given set of properties.
  37063. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37064. * @return the new set of property still marked as dirty
  37065. */
  37066. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  37067. this._instanceDirtyFlags &= ~flags;
  37068. return this._instanceDirtyFlags;
  37069. };
  37070. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  37071. this._instanceDirtyFlags = 0;
  37072. };
  37073. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  37074. /**
  37075. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  37076. */
  37077. get: function () {
  37078. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  37079. this.updateLevelBoundingInfo();
  37080. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37081. }
  37082. return this._levelBoundingInfo;
  37083. },
  37084. enumerable: true,
  37085. configurable: true
  37086. });
  37087. /**
  37088. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  37089. */
  37090. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  37091. };
  37092. /**
  37093. * Property method called when the Primitive becomes dirty
  37094. */
  37095. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  37096. };
  37097. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  37098. return function (target, propName, descriptor) {
  37099. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  37100. if (piStore) {
  37101. piStore(propInfo);
  37102. }
  37103. var getter = descriptor.get, setter = descriptor.set;
  37104. // Overload the property setter implementation to add our own logic
  37105. descriptor.set = function (val) {
  37106. // check for disposed first, do nothing
  37107. if (this.isDisposed) {
  37108. return;
  37109. }
  37110. var curVal = getter.call(this);
  37111. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  37112. return;
  37113. }
  37114. // Cast the object we're working one
  37115. var prim = this;
  37116. // Change the value
  37117. setter.call(this, val);
  37118. // Notify change, dirty flags update
  37119. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  37120. };
  37121. };
  37122. };
  37123. /**
  37124. * Add an externally attached data from its key.
  37125. * This method call will fail and return false, if such key already exists.
  37126. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  37127. * @param key the unique key that identifies the data
  37128. * @param data the data object to associate to the key for this Engine instance
  37129. * @return true if no such key were already present and the data was added successfully, false otherwise
  37130. */
  37131. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  37132. if (!this._externalData) {
  37133. this._externalData = new BABYLON.StringDictionary();
  37134. }
  37135. return this._externalData.add(key, data);
  37136. };
  37137. /**
  37138. * Get an externally attached data from its key
  37139. * @param key the unique key that identifies the data
  37140. * @return the associated data, if present (can be null), or undefined if not present
  37141. */
  37142. SmartPropertyPrim.prototype.getExternalData = function (key) {
  37143. if (!this._externalData) {
  37144. return null;
  37145. }
  37146. return this._externalData.get(key);
  37147. };
  37148. /**
  37149. * Get an externally attached data from its key, create it using a factory if it's not already present
  37150. * @param key the unique key that identifies the data
  37151. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  37152. * @return the associated data, can be null if the factory returned null.
  37153. */
  37154. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  37155. if (!this._externalData) {
  37156. this._externalData = new BABYLON.StringDictionary();
  37157. }
  37158. return this._externalData.getOrAddWithFactory(key, factory);
  37159. };
  37160. /**
  37161. * Remove an externally attached data from the Engine instance
  37162. * @param key the unique key that identifies the data
  37163. * @return true if the data was successfully removed, false if it doesn't exist
  37164. */
  37165. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  37166. if (!this._externalData) {
  37167. return false;
  37168. }
  37169. return this._externalData.remove(key);
  37170. };
  37171. /**
  37172. * Check if a given flag is set
  37173. * @param flag the flag value
  37174. * @return true if set, false otherwise
  37175. */
  37176. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  37177. return (this._flags & flag) !== 0;
  37178. };
  37179. /**
  37180. * Check if all given flags are set
  37181. * @param flags the flags ORed
  37182. * @return true if all the flags are set, false otherwise
  37183. */
  37184. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  37185. return (this._flags & flags) === flags;
  37186. };
  37187. /**
  37188. * Check if at least one flag of the given flags is set
  37189. * @param flags the flags ORed
  37190. * @return true if at least one flag is set, false otherwise
  37191. */
  37192. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  37193. return (this._flags & flags) !== 0;
  37194. };
  37195. /**
  37196. * Clear the given flags
  37197. * @param flags the flags to clear
  37198. */
  37199. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  37200. this._flags &= ~flags;
  37201. };
  37202. /**
  37203. * Set the given flags to true state
  37204. * @param flags the flags ORed to set
  37205. * @return the flags state before this call
  37206. */
  37207. SmartPropertyPrim.prototype._setFlags = function (flags) {
  37208. var cur = this._flags;
  37209. this._flags |= flags;
  37210. return cur;
  37211. };
  37212. /**
  37213. * Change the state of the given flags
  37214. * @param flags the flags ORed to change
  37215. * @param state true to set them, false to clear them
  37216. */
  37217. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  37218. if (state) {
  37219. this._flags |= flags;
  37220. }
  37221. else {
  37222. this._flags &= ~flags;
  37223. }
  37224. };
  37225. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  37226. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  37227. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  37228. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  37229. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  37230. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  37231. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  37232. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  37233. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  37234. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  37235. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  37236. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  37237. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  37238. SmartPropertyPrim = __decorate([
  37239. BABYLON.className("SmartPropertyPrim")
  37240. ], SmartPropertyPrim);
  37241. return SmartPropertyPrim;
  37242. })();
  37243. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  37244. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  37245. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37246. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37247. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  37248. }
  37249. BABYLON.modelLevelProperty = modelLevelProperty;
  37250. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  37251. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37252. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37253. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  37254. }
  37255. BABYLON.instanceLevelProperty = instanceLevelProperty;
  37256. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  37257. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37258. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37259. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  37260. }
  37261. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  37262. })(BABYLON || (BABYLON = {}));
  37263. var BABYLON;
  37264. (function (BABYLON) {
  37265. var PrepareRender2DContext = (function () {
  37266. function PrepareRender2DContext() {
  37267. this.forceRefreshPrimitive = false;
  37268. }
  37269. return PrepareRender2DContext;
  37270. })();
  37271. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  37272. var Render2DContext = (function () {
  37273. function Render2DContext(renderMode) {
  37274. this._renderMode = renderMode;
  37275. this.useInstancing = false;
  37276. this.groupInfoPartData = null;
  37277. this.partDataStartIndex = this.partDataEndIndex = null;
  37278. }
  37279. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  37280. /**
  37281. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  37282. */
  37283. get: function () {
  37284. return this._renderMode;
  37285. },
  37286. enumerable: true,
  37287. configurable: true
  37288. });
  37289. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  37290. /**
  37291. * The set of primitives to render is opaque.
  37292. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  37293. */
  37294. get: function () {
  37295. return Render2DContext._renderModeOpaque;
  37296. },
  37297. enumerable: true,
  37298. configurable: true
  37299. });
  37300. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  37301. /**
  37302. * The set of primitives to render is using Alpha Test (aka masking).
  37303. * 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.
  37304. */
  37305. get: function () {
  37306. return Render2DContext._renderModeAlphaTest;
  37307. },
  37308. enumerable: true,
  37309. configurable: true
  37310. });
  37311. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  37312. /**
  37313. * The set of primitives to render is transparent.
  37314. * 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.
  37315. */
  37316. get: function () {
  37317. return Render2DContext._renderModeTransparent;
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Render2DContext._renderModeOpaque = 1;
  37323. Render2DContext._renderModeAlphaTest = 2;
  37324. Render2DContext._renderModeTransparent = 3;
  37325. return Render2DContext;
  37326. })();
  37327. BABYLON.Render2DContext = Render2DContext;
  37328. /**
  37329. * This class store information for the pointerEventObservable Observable.
  37330. * 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.
  37331. */
  37332. var PrimitivePointerInfo = (function () {
  37333. function PrimitivePointerInfo() {
  37334. this.primitivePointerPos = BABYLON.Vector2.Zero();
  37335. this.tilt = BABYLON.Vector2.Zero();
  37336. this.cancelBubble = false;
  37337. }
  37338. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  37339. // 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.
  37340. /**
  37341. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  37342. * Bubbles: yes
  37343. */
  37344. get: function () {
  37345. return PrimitivePointerInfo._pointerOver;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  37351. /**
  37352. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  37353. * Bubbles: no
  37354. */
  37355. get: function () {
  37356. return PrimitivePointerInfo._pointerEnter;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  37362. /**
  37363. * 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.
  37364. * Bubbles: yes
  37365. */
  37366. get: function () {
  37367. return PrimitivePointerInfo._pointerDown;
  37368. },
  37369. enumerable: true,
  37370. configurable: true
  37371. });
  37372. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  37373. /**
  37374. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  37375. * Bubbles: yes
  37376. */
  37377. get: function () {
  37378. return PrimitivePointerInfo._pointerMouseWheel;
  37379. },
  37380. enumerable: true,
  37381. configurable: true
  37382. });
  37383. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  37384. /**
  37385. * 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.
  37386. * Bubbles: yes
  37387. */
  37388. get: function () {
  37389. return PrimitivePointerInfo._pointerMove;
  37390. },
  37391. enumerable: true,
  37392. configurable: true
  37393. });
  37394. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  37395. /**
  37396. * 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.
  37397. * Bubbles: yes
  37398. */
  37399. get: function () {
  37400. return PrimitivePointerInfo._pointerUp;
  37401. },
  37402. enumerable: true,
  37403. configurable: true
  37404. });
  37405. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  37406. /**
  37407. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  37408. * Bubbles: yes
  37409. */
  37410. get: function () {
  37411. return PrimitivePointerInfo._pointerOut;
  37412. },
  37413. enumerable: true,
  37414. configurable: true
  37415. });
  37416. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  37417. /**
  37418. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  37419. * Bubbles: no
  37420. */
  37421. get: function () {
  37422. return PrimitivePointerInfo._pointerLeave;
  37423. },
  37424. enumerable: true,
  37425. configurable: true
  37426. });
  37427. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  37428. /**
  37429. * 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.
  37430. * Bubbles: yes
  37431. */
  37432. get: function () {
  37433. return PrimitivePointerInfo._pointerGotCapture;
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  37439. /**
  37440. * This event type is raised after pointer capture is released for a pointer.
  37441. * Bubbles: yes
  37442. */
  37443. get: function () {
  37444. return PrimitivePointerInfo._pointerLostCapture;
  37445. },
  37446. enumerable: true,
  37447. configurable: true
  37448. });
  37449. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  37450. get: function () {
  37451. return PrimitivePointerInfo._mouseWheelPrecision;
  37452. },
  37453. enumerable: true,
  37454. configurable: true
  37455. });
  37456. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  37457. this.relatedTarget = prim;
  37458. this.relatedTargetPointerPos = primPointerPos;
  37459. };
  37460. PrimitivePointerInfo.getEventTypeName = function (mask) {
  37461. switch (mask) {
  37462. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  37463. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  37464. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  37465. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  37466. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  37467. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  37468. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  37469. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  37470. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  37471. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  37472. }
  37473. };
  37474. PrimitivePointerInfo._pointerOver = 0x0001;
  37475. PrimitivePointerInfo._pointerEnter = 0x0002;
  37476. PrimitivePointerInfo._pointerDown = 0x0004;
  37477. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  37478. PrimitivePointerInfo._pointerMove = 0x0010;
  37479. PrimitivePointerInfo._pointerUp = 0x0020;
  37480. PrimitivePointerInfo._pointerOut = 0x0040;
  37481. PrimitivePointerInfo._pointerLeave = 0x0080;
  37482. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  37483. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  37484. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  37485. return PrimitivePointerInfo;
  37486. })();
  37487. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  37488. /**
  37489. * Defines the horizontal and vertical alignment information for a Primitive.
  37490. */
  37491. var PrimitiveAlignment = (function () {
  37492. function PrimitiveAlignment(changeCallback) {
  37493. this._changedCallback = changeCallback;
  37494. this._horizontal = PrimitiveAlignment.AlignLeft;
  37495. this._vertical = PrimitiveAlignment.AlignBottom;
  37496. }
  37497. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  37498. /**
  37499. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  37500. */
  37501. get: function () { return PrimitiveAlignment._AlignLeft; },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37506. /**
  37507. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37508. */
  37509. get: function () { return PrimitiveAlignment._AlignTop; },
  37510. enumerable: true,
  37511. configurable: true
  37512. });
  37513. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37514. /**
  37515. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37516. */
  37517. get: function () { return PrimitiveAlignment._AlignRight; },
  37518. enumerable: true,
  37519. configurable: true
  37520. });
  37521. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37522. /**
  37523. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37524. */
  37525. get: function () { return PrimitiveAlignment._AlignBottom; },
  37526. enumerable: true,
  37527. configurable: true
  37528. });
  37529. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37530. /**
  37531. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37532. */
  37533. get: function () { return PrimitiveAlignment._AlignCenter; },
  37534. enumerable: true,
  37535. configurable: true
  37536. });
  37537. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37538. /**
  37539. * The content is stretched toward the opposite edges of the Primitive
  37540. */
  37541. get: function () { return PrimitiveAlignment._AlignStretch; },
  37542. enumerable: true,
  37543. configurable: true
  37544. });
  37545. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37546. /**
  37547. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37548. */
  37549. get: function () {
  37550. return this._horizontal;
  37551. },
  37552. set: function (value) {
  37553. if (this._horizontal === value) {
  37554. return;
  37555. }
  37556. this._horizontal = value;
  37557. this._changedCallback();
  37558. },
  37559. enumerable: true,
  37560. configurable: true
  37561. });
  37562. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37563. /**
  37564. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37565. */
  37566. get: function () {
  37567. return this._vertical;
  37568. },
  37569. set: function (value) {
  37570. if (this._vertical === value) {
  37571. return;
  37572. }
  37573. this._vertical = value;
  37574. this._changedCallback();
  37575. },
  37576. enumerable: true,
  37577. configurable: true
  37578. });
  37579. /**
  37580. * Set the horizontal alignment from a string value.
  37581. * @param text can be either: 'left','right','center','stretch'
  37582. */
  37583. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37584. var v = text.trim().toLocaleLowerCase();
  37585. switch (v) {
  37586. case "left":
  37587. this.horizontal = PrimitiveAlignment.AlignLeft;
  37588. return;
  37589. case "right":
  37590. this.horizontal = PrimitiveAlignment.AlignRight;
  37591. return;
  37592. case "center":
  37593. this.horizontal = PrimitiveAlignment.AlignCenter;
  37594. return;
  37595. case "stretch":
  37596. this.horizontal = PrimitiveAlignment.AlignStretch;
  37597. return;
  37598. }
  37599. };
  37600. /**
  37601. * Set the vertical alignment from a string value.
  37602. * @param text can be either: 'top','bottom','center','stretch'
  37603. */
  37604. PrimitiveAlignment.prototype.setVertical = function (text) {
  37605. var v = text.trim().toLocaleLowerCase();
  37606. switch (v) {
  37607. case "top":
  37608. this.vertical = PrimitiveAlignment.AlignTop;
  37609. return;
  37610. case "bottom":
  37611. this.vertical = PrimitiveAlignment.AlignBottom;
  37612. return;
  37613. case "center":
  37614. this.vertical = PrimitiveAlignment.AlignCenter;
  37615. return;
  37616. case "stretch":
  37617. this.vertical = PrimitiveAlignment.AlignStretch;
  37618. return;
  37619. }
  37620. };
  37621. /**
  37622. * Set the horizontal and or vertical alignments from a string value.
  37623. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  37624. */
  37625. PrimitiveAlignment.prototype.fromString = function (value) {
  37626. var m = value.trim().split(",");
  37627. for (var _i = 0; _i < m.length; _i++) {
  37628. var v = m[_i];
  37629. v = v.toLocaleLowerCase().trim();
  37630. // Horizontal
  37631. var i = v.indexOf("h:");
  37632. if (i === -1) {
  37633. i = v.indexOf("horizontal:");
  37634. }
  37635. if (i !== -1) {
  37636. v = v.substr(v.indexOf(":") + 1);
  37637. this.setHorizontal(v);
  37638. continue;
  37639. }
  37640. // Vertical
  37641. i = v.indexOf("v:");
  37642. if (i === -1) {
  37643. i = v.indexOf("vertical:");
  37644. }
  37645. if (i !== -1) {
  37646. v = v.substr(v.indexOf(":") + 1);
  37647. this.setVertical(v);
  37648. continue;
  37649. }
  37650. }
  37651. };
  37652. PrimitiveAlignment._AlignLeft = 1;
  37653. PrimitiveAlignment._AlignTop = 1; // Same as left
  37654. PrimitiveAlignment._AlignRight = 2;
  37655. PrimitiveAlignment._AlignBottom = 2; // Same as right
  37656. PrimitiveAlignment._AlignCenter = 3;
  37657. PrimitiveAlignment._AlignStretch = 4;
  37658. return PrimitiveAlignment;
  37659. })();
  37660. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  37661. /**
  37662. * Stores information about a Primitive that was intersected
  37663. */
  37664. var PrimitiveIntersectedInfo = (function () {
  37665. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  37666. this.prim = prim;
  37667. this.intersectionLocation = intersectionLocation;
  37668. }
  37669. return PrimitiveIntersectedInfo;
  37670. })();
  37671. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  37672. /**
  37673. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  37674. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  37675. */
  37676. var PrimitiveThickness = (function () {
  37677. function PrimitiveThickness(parentAccess, changedCallback) {
  37678. this._parentAccess = parentAccess;
  37679. this._changedCallback = changedCallback;
  37680. this._pixels = new Array(4);
  37681. this._percentages = new Array(4);
  37682. this._setType(0, PrimitiveThickness.Auto);
  37683. this._setType(1, PrimitiveThickness.Auto);
  37684. this._setType(2, PrimitiveThickness.Auto);
  37685. this._setType(3, PrimitiveThickness.Auto);
  37686. this._pixels[0] = 0;
  37687. this._pixels[1] = 0;
  37688. this._pixels[2] = 0;
  37689. this._pixels[3] = 0;
  37690. }
  37691. /**
  37692. * Set the thickness from a string value
  37693. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" each are optional, auto will be set if it's omitted.
  37694. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37695. */
  37696. PrimitiveThickness.prototype.fromString = function (thickness) {
  37697. this._clear();
  37698. var m = thickness.trim().split(",");
  37699. var res = false;
  37700. for (var _i = 0; _i < m.length; _i++) {
  37701. var cm = m[_i];
  37702. res = this._extractString(cm, false) || res;
  37703. }
  37704. if (!res) {
  37705. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  37706. }
  37707. // Check the margin that weren't set and set them in auto
  37708. if ((this._flags & 0x000F) === 0)
  37709. this._flags |= PrimitiveThickness.Pixel << 0;
  37710. if ((this._flags & 0x00F0) === 0)
  37711. this._flags |= PrimitiveThickness.Pixel << 4;
  37712. if ((this._flags & 0x0F00) === 0)
  37713. this._flags |= PrimitiveThickness.Pixel << 8;
  37714. if ((this._flags & 0xF000) === 0)
  37715. this._flags |= PrimitiveThickness.Pixel << 12;
  37716. this._changedCallback();
  37717. };
  37718. /**
  37719. * Set the thickness from multiple string
  37720. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37721. * @param top the top thickness to set
  37722. * @param left the left thickness to set
  37723. * @param right the right thickness to set
  37724. * @param bottom the bottom thickness to set
  37725. */
  37726. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  37727. this._clear();
  37728. this._setStringValue(top, 0, false);
  37729. this._setStringValue(left, 1, false);
  37730. this._setStringValue(right, 2, false);
  37731. this._setStringValue(bottom, 3, false);
  37732. this._changedCallback();
  37733. return this;
  37734. };
  37735. /**
  37736. * Set the thickness from pixel values
  37737. * @param top the top thickness in pixels to set
  37738. * @param left the left thickness in pixels to set
  37739. * @param right the right thickness in pixels to set
  37740. * @param bottom the bottom thickness in pixels to set
  37741. */
  37742. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  37743. this._clear();
  37744. this._pixels[0] = top;
  37745. this._pixels[1] = left;
  37746. this._pixels[2] = right;
  37747. this._pixels[3] = bottom;
  37748. this._changedCallback();
  37749. return this;
  37750. };
  37751. /**
  37752. * Apply the same pixel value to all edges
  37753. * @param margin the value to set, in pixels.
  37754. */
  37755. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  37756. this._clear();
  37757. this._pixels[0] = margin;
  37758. this._pixels[1] = margin;
  37759. this._pixels[2] = margin;
  37760. this._pixels[3] = margin;
  37761. this._changedCallback();
  37762. return this;
  37763. };
  37764. /**
  37765. * Set all edges in auto
  37766. */
  37767. PrimitiveThickness.prototype.auto = function () {
  37768. this._clear();
  37769. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  37770. this._pixels[0] = 0;
  37771. this._pixels[1] = 0;
  37772. this._pixels[2] = 0;
  37773. this._pixels[3] = 0;
  37774. this._changedCallback();
  37775. return this;
  37776. };
  37777. PrimitiveThickness.prototype._clear = function () {
  37778. this._flags = 0;
  37779. this._pixels[0] = 0;
  37780. this._pixels[1] = 0;
  37781. this._pixels[2] = 0;
  37782. this._pixels[3] = 0;
  37783. this._percentages[0] = null;
  37784. this._percentages[1] = null;
  37785. this._percentages[2] = null;
  37786. this._percentages[3] = null;
  37787. };
  37788. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  37789. var v = value.trim().toLocaleLowerCase();
  37790. if (v.indexOf("top:") === 0) {
  37791. v = v.substr(4).trim();
  37792. return this._setStringValue(v, 0, emitChanged);
  37793. }
  37794. if (v.indexOf("left:") === 0) {
  37795. v = v.substr(5).trim();
  37796. return this._setStringValue(v, 1, emitChanged);
  37797. }
  37798. if (v.indexOf("right:") === 0) {
  37799. v = v.substr(6).trim();
  37800. return this._setStringValue(v, 2, emitChanged);
  37801. }
  37802. if (v.indexOf("bottom:") === 0) {
  37803. v = v.substr(7).trim();
  37804. return this._setStringValue(v, 3, emitChanged);
  37805. }
  37806. return false;
  37807. };
  37808. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  37809. // Check for auto
  37810. var v = value.trim().toLocaleLowerCase();
  37811. if (v === "auto") {
  37812. if (this._isType(index, PrimitiveThickness.Auto)) {
  37813. return true;
  37814. }
  37815. this._setType(index, PrimitiveThickness.Auto);
  37816. this._pixels[index] = 0;
  37817. if (emitChanged) {
  37818. this._changedCallback();
  37819. }
  37820. }
  37821. else if (v === "inherit") {
  37822. if (this._isType(index, PrimitiveThickness.Inherit)) {
  37823. return true;
  37824. }
  37825. this._setType(index, PrimitiveThickness.Inherit);
  37826. this._pixels[index] = null;
  37827. if (emitChanged) {
  37828. this._changedCallback();
  37829. }
  37830. }
  37831. else {
  37832. var pI = v.indexOf("%");
  37833. // Check for percentage
  37834. if (pI !== -1) {
  37835. var n_1 = v.substr(0, pI);
  37836. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  37837. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  37838. return true;
  37839. }
  37840. this._setType(index, PrimitiveThickness.Percentage);
  37841. if (isNaN(number_1)) {
  37842. return false;
  37843. }
  37844. this._percentages[index] = number_1;
  37845. if (emitChanged) {
  37846. this._changedCallback();
  37847. }
  37848. return true;
  37849. }
  37850. // Check for pixel
  37851. var n;
  37852. pI = v.indexOf("px");
  37853. if (pI !== -1) {
  37854. n = v.substr(0, pI).trim();
  37855. }
  37856. else {
  37857. n = v;
  37858. }
  37859. var number = Number(n);
  37860. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  37861. return true;
  37862. }
  37863. if (isNaN(number)) {
  37864. return false;
  37865. }
  37866. this._pixels[index] = number;
  37867. this._setType(index, PrimitiveThickness.Pixel);
  37868. if (emitChanged) {
  37869. this._changedCallback();
  37870. }
  37871. return true;
  37872. }
  37873. };
  37874. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  37875. // 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
  37876. value = Math.round(value);
  37877. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  37878. return;
  37879. }
  37880. this._setType(index, PrimitiveThickness.Pixel);
  37881. this._pixels[index] = value;
  37882. if (emitChanged) {
  37883. this._changedCallback();
  37884. }
  37885. };
  37886. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  37887. // Clip Value to bounds
  37888. value = Math.min(1, value);
  37889. value = Math.max(0, value);
  37890. value = Math.round(value * 100) / 100; // 0.01 precision
  37891. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  37892. return;
  37893. }
  37894. this._setType(index, PrimitiveThickness.Percentage);
  37895. this._percentages[index] = value;
  37896. if (emitChanged) {
  37897. this._changedCallback();
  37898. }
  37899. };
  37900. PrimitiveThickness.prototype._getStringValue = function (index) {
  37901. var f = (this._flags >> (index * 4)) & 0xF;
  37902. switch (f) {
  37903. case PrimitiveThickness.Auto:
  37904. return "auto";
  37905. case PrimitiveThickness.Pixel:
  37906. return this._pixels[index] + "px";
  37907. case PrimitiveThickness.Percentage:
  37908. return this._percentages[index] * 100 + "%";
  37909. case PrimitiveThickness.Inherit:
  37910. return "inherit";
  37911. }
  37912. return "";
  37913. };
  37914. PrimitiveThickness.prototype._isType = function (index, type) {
  37915. var f = (this._flags >> (index * 4)) & 0xF;
  37916. return f === type;
  37917. };
  37918. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  37919. var t = (this._flags >> (index * 4)) & 0xF;
  37920. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  37921. var p = this._parentAccess();
  37922. if (p) {
  37923. return p._getType(index, true);
  37924. }
  37925. return PrimitiveThickness.Auto;
  37926. }
  37927. return t;
  37928. };
  37929. PrimitiveThickness.prototype._setType = function (index, type) {
  37930. this._flags &= ~(0xF << (index * 4));
  37931. this._flags |= type << (index * 4);
  37932. };
  37933. PrimitiveThickness.prototype.setTop = function (value) {
  37934. if (typeof value === "string") {
  37935. this._setStringValue(value, 0, true);
  37936. }
  37937. else {
  37938. this.topPixels = value;
  37939. }
  37940. };
  37941. PrimitiveThickness.prototype.setLeft = function (value) {
  37942. if (typeof value === "string") {
  37943. this._setStringValue(value, 1, true);
  37944. }
  37945. else {
  37946. this.leftPixels = value;
  37947. }
  37948. };
  37949. PrimitiveThickness.prototype.setRight = function (value) {
  37950. if (typeof value === "string") {
  37951. this._setStringValue(value, 2, true);
  37952. }
  37953. else {
  37954. this.rightPixels = value;
  37955. }
  37956. };
  37957. PrimitiveThickness.prototype.setBottom = function (value) {
  37958. if (typeof value === "string") {
  37959. this._setStringValue(value, 3, true);
  37960. }
  37961. else {
  37962. this.bottomPixels = value;
  37963. }
  37964. };
  37965. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  37966. /**
  37967. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37968. */
  37969. get: function () {
  37970. return this._getStringValue(0);
  37971. },
  37972. set: function (value) {
  37973. this._setStringValue(value, 0, true);
  37974. },
  37975. enumerable: true,
  37976. configurable: true
  37977. });
  37978. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  37979. /**
  37980. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37981. */
  37982. get: function () {
  37983. return this._getStringValue(1);
  37984. },
  37985. set: function (value) {
  37986. this._setStringValue(value, 1, true);
  37987. },
  37988. enumerable: true,
  37989. configurable: true
  37990. });
  37991. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  37992. /**
  37993. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37994. */
  37995. get: function () {
  37996. return this._getStringValue(2);
  37997. },
  37998. set: function (value) {
  37999. this._setStringValue(value, 2, true);
  38000. },
  38001. enumerable: true,
  38002. configurable: true
  38003. });
  38004. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38005. /**
  38006. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38007. */
  38008. get: function () {
  38009. return this._getStringValue(3);
  38010. },
  38011. set: function (value) {
  38012. this._setStringValue(value, 3, true);
  38013. },
  38014. enumerable: true,
  38015. configurable: true
  38016. });
  38017. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  38018. /**
  38019. * Get/set the top thickness in pixel.
  38020. */
  38021. get: function () {
  38022. return this._pixels[0];
  38023. },
  38024. set: function (value) {
  38025. this._setPixels(value, 0, true);
  38026. },
  38027. enumerable: true,
  38028. configurable: true
  38029. });
  38030. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  38031. /**
  38032. * Get/set the left thickness in pixel.
  38033. */
  38034. get: function () {
  38035. return this._pixels[1];
  38036. },
  38037. set: function (value) {
  38038. this._setPixels(value, 1, true);
  38039. },
  38040. enumerable: true,
  38041. configurable: true
  38042. });
  38043. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  38044. /**
  38045. * Get/set the right thickness in pixel.
  38046. */
  38047. get: function () {
  38048. return this._pixels[2];
  38049. },
  38050. set: function (value) {
  38051. this._setPixels(value, 2, true);
  38052. },
  38053. enumerable: true,
  38054. configurable: true
  38055. });
  38056. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  38057. /**
  38058. * Get/set the bottom thickness in pixel.
  38059. */
  38060. get: function () {
  38061. return this._pixels[3];
  38062. },
  38063. set: function (value) {
  38064. this._setPixels(value, 3, true);
  38065. },
  38066. enumerable: true,
  38067. configurable: true
  38068. });
  38069. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  38070. /**
  38071. * Get/set the top thickness in percentage.
  38072. * The get will return a valid value only if the edge type is percentage.
  38073. * The Set will change the edge mode if needed
  38074. */
  38075. get: function () {
  38076. return this._percentages[0];
  38077. },
  38078. set: function (value) {
  38079. this._setPercentage(value, 0, true);
  38080. },
  38081. enumerable: true,
  38082. configurable: true
  38083. });
  38084. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  38085. /**
  38086. * Get/set the left thickness in percentage.
  38087. * The get will return a valid value only if the edge mode is percentage.
  38088. * The Set will change the edge mode if needed
  38089. */
  38090. get: function () {
  38091. return this._percentages[1];
  38092. },
  38093. set: function (value) {
  38094. this._setPercentage(value, 1, true);
  38095. },
  38096. enumerable: true,
  38097. configurable: true
  38098. });
  38099. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  38100. /**
  38101. * Get/set the right thickness in percentage.
  38102. * The get will return a valid value only if the edge mode is percentage.
  38103. * The Set will change the edge mode if needed
  38104. */
  38105. get: function () {
  38106. return this._percentages[2];
  38107. },
  38108. set: function (value) {
  38109. this._setPercentage(value, 2, true);
  38110. },
  38111. enumerable: true,
  38112. configurable: true
  38113. });
  38114. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  38115. /**
  38116. * Get/set the bottom thickness in percentage.
  38117. * The get will return a valid value only if the edge mode is percentage.
  38118. * The Set will change the edge mode if needed
  38119. */
  38120. get: function () {
  38121. return this._percentages[3];
  38122. },
  38123. set: function (value) {
  38124. this._setPercentage(value, 3, true);
  38125. },
  38126. enumerable: true,
  38127. configurable: true
  38128. });
  38129. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  38130. /**
  38131. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  38132. */
  38133. get: function () {
  38134. return this._getType(0, false);
  38135. },
  38136. set: function (mode) {
  38137. this._setType(0, mode);
  38138. },
  38139. enumerable: true,
  38140. configurable: true
  38141. });
  38142. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  38143. /**
  38144. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  38145. */
  38146. get: function () {
  38147. return this._getType(1, false);
  38148. },
  38149. set: function (mode) {
  38150. this._setType(1, mode);
  38151. },
  38152. enumerable: true,
  38153. configurable: true
  38154. });
  38155. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  38156. /**
  38157. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  38158. */
  38159. get: function () {
  38160. return this._getType(2, false);
  38161. },
  38162. set: function (mode) {
  38163. this._setType(2, mode);
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  38169. /**
  38170. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  38171. */
  38172. get: function () {
  38173. return this._getType(3, false);
  38174. },
  38175. set: function (mode) {
  38176. this._setType(3, mode);
  38177. },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  38182. var type = this._getType(index, false);
  38183. if (type === PrimitiveThickness.Inherit) {
  38184. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  38185. return;
  38186. }
  38187. if (type !== PrimitiveThickness.Percentage) {
  38188. return;
  38189. }
  38190. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  38191. this._pixels[index] = pixels;
  38192. if (emitChanged) {
  38193. this._changedCallback();
  38194. }
  38195. };
  38196. /**
  38197. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  38198. * @param sourceArea the source area
  38199. * @param contentSize the content size to position/resize
  38200. * @param alignment the alignment setting
  38201. * @param dstOffset the position of the content
  38202. * @param dstArea the new size of the content
  38203. */
  38204. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  38205. // Fetch some data
  38206. var topType = this._getType(0, true);
  38207. var leftType = this._getType(1, true);
  38208. var rightType = this._getType(2, true);
  38209. var bottomType = this._getType(3, true);
  38210. var hasWidth = contentSize && (contentSize.width != null);
  38211. var hasHeight = contentSize && (contentSize.height != null);
  38212. var width = hasWidth ? contentSize.width : 0;
  38213. var height = hasHeight ? contentSize.height : 0;
  38214. var isTopAuto = topType === PrimitiveThickness.Auto;
  38215. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  38216. var isRightAuto = rightType === PrimitiveThickness.Auto;
  38217. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  38218. switch (alignment.horizontal) {
  38219. case PrimitiveAlignment.AlignLeft:
  38220. {
  38221. if (isLeftAuto) {
  38222. dstOffset.x = 0;
  38223. }
  38224. else {
  38225. this._computePixels(1, sourceArea, true);
  38226. dstOffset.x = this.leftPixels;
  38227. }
  38228. dstArea.width = width;
  38229. break;
  38230. }
  38231. case PrimitiveAlignment.AlignRight:
  38232. {
  38233. if (isRightAuto) {
  38234. dstOffset.x = Math.round(sourceArea.width - width);
  38235. }
  38236. else {
  38237. this._computePixels(2, sourceArea, true);
  38238. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  38239. }
  38240. dstArea.width = width;
  38241. break;
  38242. }
  38243. case PrimitiveAlignment.AlignStretch:
  38244. {
  38245. if (isLeftAuto) {
  38246. dstOffset.x = 0;
  38247. }
  38248. else {
  38249. this._computePixels(1, sourceArea, true);
  38250. dstOffset.x = this.leftPixels;
  38251. }
  38252. var right = 0;
  38253. if (!isRightAuto) {
  38254. this._computePixels(2, sourceArea, true);
  38255. right = this.rightPixels;
  38256. }
  38257. dstArea.width = sourceArea.width - (dstOffset.x + right);
  38258. break;
  38259. }
  38260. case PrimitiveAlignment.AlignCenter:
  38261. {
  38262. if (!isLeftAuto) {
  38263. this._computePixels(1, sourceArea, true);
  38264. }
  38265. if (!isRightAuto) {
  38266. this._computePixels(2, sourceArea, true);
  38267. }
  38268. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  38269. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  38270. dstArea.width = width;
  38271. break;
  38272. }
  38273. }
  38274. switch (alignment.vertical) {
  38275. case PrimitiveAlignment.AlignTop:
  38276. {
  38277. if (isTopAuto) {
  38278. dstOffset.y = sourceArea.height - height;
  38279. }
  38280. else {
  38281. this._computePixels(0, sourceArea, true);
  38282. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  38283. }
  38284. dstArea.height = height;
  38285. break;
  38286. }
  38287. case PrimitiveAlignment.AlignBottom:
  38288. {
  38289. if (isBottomAuto) {
  38290. dstOffset.y = 0;
  38291. }
  38292. else {
  38293. this._computePixels(3, sourceArea, true);
  38294. dstOffset.y = this.bottomPixels;
  38295. }
  38296. dstArea.height = height;
  38297. break;
  38298. }
  38299. case PrimitiveAlignment.AlignStretch:
  38300. {
  38301. if (isBottomAuto) {
  38302. dstOffset.y = 0;
  38303. }
  38304. else {
  38305. this._computePixels(3, sourceArea, true);
  38306. dstOffset.y = this.bottomPixels;
  38307. }
  38308. var top_1 = 0;
  38309. if (!isTopAuto) {
  38310. this._computePixels(0, sourceArea, true);
  38311. top_1 = this.topPixels;
  38312. }
  38313. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  38314. break;
  38315. }
  38316. case PrimitiveAlignment.AlignCenter:
  38317. {
  38318. if (!isTopAuto) {
  38319. this._computePixels(0, sourceArea, true);
  38320. }
  38321. if (!isBottomAuto) {
  38322. this._computePixels(3, sourceArea, true);
  38323. }
  38324. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  38325. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  38326. dstArea.height = height;
  38327. break;
  38328. }
  38329. }
  38330. };
  38331. /**
  38332. * Compute an area and its position considering this thickness properties based on a given source area
  38333. * @param sourceArea the source area
  38334. * @param dstOffset the position of the resulting area
  38335. * @param dstArea the size of the resulting area
  38336. */
  38337. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  38338. this._computePixels(0, sourceArea, true);
  38339. this._computePixels(1, sourceArea, true);
  38340. this._computePixels(2, sourceArea, true);
  38341. this._computePixels(3, sourceArea, true);
  38342. dstOffset.x = this.leftPixels;
  38343. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  38344. dstOffset.y = this.bottomPixels;
  38345. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  38346. };
  38347. /**
  38348. * Compute an area considering this thickness properties based on a given source area
  38349. * @param sourceArea the source area
  38350. * @param result the resulting area
  38351. */
  38352. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  38353. this._computePixels(0, sourceArea, true);
  38354. this._computePixels(1, sourceArea, true);
  38355. this._computePixels(2, sourceArea, true);
  38356. this._computePixels(3, sourceArea, true);
  38357. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  38358. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  38359. };
  38360. PrimitiveThickness.Auto = 0x1;
  38361. PrimitiveThickness.Inherit = 0x2;
  38362. PrimitiveThickness.Percentage = 0x4;
  38363. PrimitiveThickness.Pixel = 0x8;
  38364. return PrimitiveThickness;
  38365. })();
  38366. BABYLON.PrimitiveThickness = PrimitiveThickness;
  38367. /**
  38368. * Main class used for the Primitive Intersection API
  38369. */
  38370. var IntersectInfo2D = (function () {
  38371. function IntersectInfo2D() {
  38372. this.findFirstOnly = false;
  38373. this.intersectHidden = false;
  38374. this.pickPosition = BABYLON.Vector2.Zero();
  38375. }
  38376. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  38377. /**
  38378. * true if at least one primitive intersected during the test
  38379. */
  38380. get: function () {
  38381. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  38382. },
  38383. enumerable: true,
  38384. configurable: true
  38385. });
  38386. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  38387. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  38388. var cur = _a[_i];
  38389. if (cur.prim === prim) {
  38390. return cur.intersectionLocation;
  38391. }
  38392. }
  38393. return null;
  38394. };
  38395. // Internals, don't use
  38396. IntersectInfo2D.prototype._exit = function (firstLevel) {
  38397. if (firstLevel) {
  38398. this._globalPickPosition = null;
  38399. }
  38400. };
  38401. return IntersectInfo2D;
  38402. })();
  38403. BABYLON.IntersectInfo2D = IntersectInfo2D;
  38404. var Prim2DBase = (function (_super) {
  38405. __extends(Prim2DBase, _super);
  38406. function Prim2DBase(settings) {
  38407. // Avoid checking every time if the object exists
  38408. if (settings == null) {
  38409. settings = {};
  38410. }
  38411. // BASE CLASS CALL
  38412. _super.call(this);
  38413. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  38414. var owner;
  38415. var parent;
  38416. if (Prim2DBase._isCanvasInit) {
  38417. owner = this;
  38418. parent = null;
  38419. this._canvasPreInit(settings);
  38420. }
  38421. else {
  38422. if (settings.parent != null) {
  38423. parent = settings.parent;
  38424. owner = settings.parent.owner;
  38425. if (!owner) {
  38426. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  38427. }
  38428. 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)) {
  38429. 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");
  38430. }
  38431. }
  38432. }
  38433. // Fields initialization
  38434. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38435. this._size = null; //Size.Zero();
  38436. this._actualSize = null;
  38437. this._boundingSize = null;
  38438. this._layoutArea = BABYLON.Size.Zero();
  38439. this._layoutAreaPos = BABYLON.Vector2.Zero();
  38440. this._marginOffset = BABYLON.Vector2.Zero();
  38441. this._parentMargingOffset = BABYLON.Vector2.Zero();
  38442. this._parentContentArea = BABYLON.Size.Zero();
  38443. this._contentArea = new BABYLON.Size(null, null);
  38444. this._pointerEventObservable = new BABYLON.Observable();
  38445. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  38446. this._boundingInfo = new BABYLON.BoundingInfo2D();
  38447. this._owner = owner;
  38448. this._parent = null;
  38449. this._margin = null;
  38450. this._padding = null;
  38451. this._marginAlignment = null;
  38452. this._id = settings.id;
  38453. this.propertyChanged = new BABYLON.Observable();
  38454. this._children = new Array();
  38455. this._localTransform = new BABYLON.Matrix();
  38456. this._globalTransform = null;
  38457. this._invGlobalTransform = null;
  38458. this._globalTransformProcessStep = 0;
  38459. this._globalTransformStep = 0;
  38460. this._hierarchyDepth = 0;
  38461. this._renderGroup = null;
  38462. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  38463. // If the parent is given, initialize the hierarchy/owner related data
  38464. if (parent != null) {
  38465. parent.addChild(this);
  38466. this._patchHierarchy(parent.owner);
  38467. }
  38468. // If it's a group, detect its own states
  38469. if (this.owner && this instanceof BABYLON.Group2D) {
  38470. var group = this;
  38471. group.detectGroupStates();
  38472. }
  38473. // Time to insert children if some are specified
  38474. if (settings.children != null) {
  38475. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  38476. var child = _a[_i];
  38477. this.addChild(child);
  38478. // Good time to patch the hierarchy, it won't go very far if there's no need to
  38479. child._patchHierarchy(this.owner);
  38480. }
  38481. }
  38482. // Set the model related properties
  38483. if (settings.position != null) {
  38484. this.position = settings.position;
  38485. }
  38486. else if (settings.x != null || settings.y != null) {
  38487. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  38488. }
  38489. else {
  38490. this._position = null;
  38491. }
  38492. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  38493. this.scale = (settings.scale == null) ? 1 : settings.scale;
  38494. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  38495. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  38496. // Layout Engine
  38497. if (settings.layoutEngine != null) {
  38498. if (typeof settings.layoutEngine === "string") {
  38499. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  38500. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  38501. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38502. }
  38503. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  38504. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38505. }
  38506. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38507. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38508. }
  38509. }
  38510. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38511. this.layoutEngine = settings.layoutEngine;
  38512. }
  38513. }
  38514. // Set the layout/margin stuffs
  38515. if (settings.marginTop) {
  38516. this.margin.setTop(settings.marginTop);
  38517. }
  38518. if (settings.marginLeft) {
  38519. this.margin.setLeft(settings.marginLeft);
  38520. }
  38521. if (settings.marginRight) {
  38522. this.margin.setRight(settings.marginRight);
  38523. }
  38524. if (settings.marginBottom) {
  38525. this.margin.setBottom(settings.marginBottom);
  38526. }
  38527. if (settings.margin) {
  38528. if (typeof settings.margin === "string") {
  38529. this.margin.fromString(settings.margin);
  38530. }
  38531. else {
  38532. this.margin.fromUniformPixels(settings.margin);
  38533. }
  38534. }
  38535. if (settings.marginHAlignment) {
  38536. this.marginAlignment.horizontal = settings.marginHAlignment;
  38537. }
  38538. if (settings.marginVAlignment) {
  38539. this.marginAlignment.vertical = settings.marginVAlignment;
  38540. }
  38541. if (settings.marginAlignment) {
  38542. this.marginAlignment.fromString(settings.marginAlignment);
  38543. }
  38544. if (settings.paddingTop) {
  38545. this.padding.setTop(settings.paddingTop);
  38546. }
  38547. if (settings.paddingLeft) {
  38548. this.padding.setLeft(settings.paddingLeft);
  38549. }
  38550. if (settings.paddingRight) {
  38551. this.padding.setRight(settings.paddingRight);
  38552. }
  38553. if (settings.paddingBottom) {
  38554. this.padding.setBottom(settings.paddingBottom);
  38555. }
  38556. if (settings.padding) {
  38557. this.padding.fromString(settings.padding);
  38558. }
  38559. // Dirty layout and positioning
  38560. this._parentLayoutDirty();
  38561. this._positioningDirty();
  38562. }
  38563. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  38564. get: function () {
  38565. if (!this._actionManager) {
  38566. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  38567. }
  38568. return this._actionManager;
  38569. },
  38570. enumerable: true,
  38571. configurable: true
  38572. });
  38573. /**
  38574. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  38575. * @param predicate the predicate to test on each parent
  38576. * @return the first primitive where the predicate was successful
  38577. */
  38578. Prim2DBase.prototype.traverseUp = function (predicate) {
  38579. var p = this;
  38580. while (p != null) {
  38581. if (predicate(p)) {
  38582. return p;
  38583. }
  38584. p = p._parent;
  38585. }
  38586. return null;
  38587. };
  38588. Object.defineProperty(Prim2DBase.prototype, "owner", {
  38589. /**
  38590. * Retrieve the owner Canvas2D
  38591. */
  38592. get: function () {
  38593. return this._owner;
  38594. },
  38595. enumerable: true,
  38596. configurable: true
  38597. });
  38598. Object.defineProperty(Prim2DBase.prototype, "parent", {
  38599. /**
  38600. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  38601. */
  38602. get: function () {
  38603. return this._parent;
  38604. },
  38605. enumerable: true,
  38606. configurable: true
  38607. });
  38608. Object.defineProperty(Prim2DBase.prototype, "children", {
  38609. /**
  38610. * The array of direct children primitives
  38611. */
  38612. get: function () {
  38613. return this._children;
  38614. },
  38615. enumerable: true,
  38616. configurable: true
  38617. });
  38618. Object.defineProperty(Prim2DBase.prototype, "id", {
  38619. /**
  38620. * The identifier of this primitive, may not be unique, it's for information purpose only
  38621. */
  38622. get: function () {
  38623. return this._id;
  38624. },
  38625. enumerable: true,
  38626. configurable: true
  38627. });
  38628. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  38629. get: function () {
  38630. if (this._actualPosition != null) {
  38631. return this._actualPosition;
  38632. }
  38633. if (this._position != null) {
  38634. return this._position;
  38635. }
  38636. // At least return 0,0, we can't return null on actualPosition
  38637. return Prim2DBase._nullPosition;
  38638. },
  38639. /**
  38640. * DO NOT INVOKE for internal purpose only
  38641. */
  38642. set: function (val) {
  38643. this._actualPosition = val;
  38644. },
  38645. enumerable: true,
  38646. configurable: true
  38647. });
  38648. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  38649. /**
  38650. * Shortcut to actualPosition.x
  38651. */
  38652. get: function () {
  38653. return this.actualPosition.x;
  38654. },
  38655. enumerable: true,
  38656. configurable: true
  38657. });
  38658. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  38659. /**
  38660. * Shortcut to actualPosition.y
  38661. */
  38662. get: function () {
  38663. return this.actualPosition.y;
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. Object.defineProperty(Prim2DBase.prototype, "position", {
  38669. /**
  38670. * Position of the primitive, relative to its parent.
  38671. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  38672. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  38673. * Setting this property may have no effect is specific alignment are in effect.
  38674. */
  38675. get: function () {
  38676. return this._position;
  38677. },
  38678. set: function (value) {
  38679. if (!this._checkPositionChange()) {
  38680. return;
  38681. }
  38682. this._position = value;
  38683. },
  38684. enumerable: true,
  38685. configurable: true
  38686. });
  38687. Object.defineProperty(Prim2DBase.prototype, "x", {
  38688. /**
  38689. * Direct access to the position.x value of the primitive
  38690. * Use this property when you only want to change one component of the position property
  38691. */
  38692. get: function () {
  38693. if (!this._position) {
  38694. return null;
  38695. }
  38696. return this._position.x;
  38697. },
  38698. set: function (value) {
  38699. if (!this._checkPositionChange()) {
  38700. return;
  38701. }
  38702. if (!this._position) {
  38703. this._position = BABYLON.Vector2.Zero();
  38704. }
  38705. if (this._position.x === value) {
  38706. return;
  38707. }
  38708. this._position.x = value;
  38709. this.markAsDirty("position");
  38710. },
  38711. enumerable: true,
  38712. configurable: true
  38713. });
  38714. Object.defineProperty(Prim2DBase.prototype, "y", {
  38715. /**
  38716. * Direct access to the position.y value of the primitive
  38717. * Use this property when you only want to change one component of the position property
  38718. */
  38719. get: function () {
  38720. if (!this._position) {
  38721. return null;
  38722. }
  38723. return this._position.y;
  38724. },
  38725. set: function (value) {
  38726. if (!this._checkPositionChange()) {
  38727. return;
  38728. }
  38729. if (!this._position) {
  38730. this._position = BABYLON.Vector2.Zero();
  38731. }
  38732. if (this._position.y === value) {
  38733. return;
  38734. }
  38735. this._position.y = value;
  38736. this.markAsDirty("position");
  38737. },
  38738. enumerable: true,
  38739. configurable: true
  38740. });
  38741. Object.defineProperty(Prim2DBase.prototype, "size", {
  38742. /**
  38743. * Size of the primitive or its bounding area
  38744. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  38745. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  38746. */
  38747. get: function () {
  38748. if (!this._size || this._size.width == null || this._size.height == null) {
  38749. if (Prim2DBase.boundinbBoxReentrency) {
  38750. return Prim2DBase.nullSize;
  38751. }
  38752. if (this._boundingSize) {
  38753. return this._boundingSize;
  38754. }
  38755. Prim2DBase.boundinbBoxReentrency = true;
  38756. var b = this.boundingInfo;
  38757. Prim2DBase.boundinbBoxReentrency = false;
  38758. return this._boundingSize;
  38759. }
  38760. return this._size;
  38761. },
  38762. set: function (value) {
  38763. this._size = value;
  38764. },
  38765. enumerable: true,
  38766. configurable: true
  38767. });
  38768. Object.defineProperty(Prim2DBase.prototype, "width", {
  38769. /**
  38770. * Direct access to the size.width value of the primitive
  38771. * Use this property when you only want to change one component of the size property
  38772. */
  38773. get: function () {
  38774. if (!this.size) {
  38775. return null;
  38776. }
  38777. return this.size.width;
  38778. },
  38779. set: function (value) {
  38780. if (!this.size) {
  38781. this.size = new BABYLON.Size(value, 0);
  38782. return;
  38783. }
  38784. if (this.size.width === value) {
  38785. return;
  38786. }
  38787. this.size.width = value;
  38788. this.markAsDirty("size");
  38789. this._positioningDirty();
  38790. },
  38791. enumerable: true,
  38792. configurable: true
  38793. });
  38794. Object.defineProperty(Prim2DBase.prototype, "height", {
  38795. /**
  38796. * Direct access to the size.height value of the primitive
  38797. * Use this property when you only want to change one component of the size property
  38798. */
  38799. get: function () {
  38800. if (!this.size) {
  38801. return null;
  38802. }
  38803. return this.size.height;
  38804. },
  38805. set: function (value) {
  38806. if (!this.size) {
  38807. this.size = new BABYLON.Size(0, value);
  38808. return;
  38809. }
  38810. if (this.size.height === value) {
  38811. return;
  38812. }
  38813. this.size.height = value;
  38814. this.markAsDirty("size");
  38815. this._positioningDirty();
  38816. },
  38817. enumerable: true,
  38818. configurable: true
  38819. });
  38820. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  38821. get: function () {
  38822. return this._rotation;
  38823. },
  38824. set: function (value) {
  38825. this._rotation = value;
  38826. },
  38827. enumerable: true,
  38828. configurable: true
  38829. });
  38830. Object.defineProperty(Prim2DBase.prototype, "scale", {
  38831. get: function () {
  38832. return this._scale;
  38833. },
  38834. set: function (value) {
  38835. this._scale = value;
  38836. },
  38837. enumerable: true,
  38838. configurable: true
  38839. });
  38840. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  38841. /**
  38842. * Return the size of the primitive as it's being rendered into the target.
  38843. * 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.
  38844. * BEWARE: don't use the setter, it's for internal purpose only
  38845. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  38846. */
  38847. get: function () {
  38848. if (this._actualSize) {
  38849. return this._actualSize;
  38850. }
  38851. return this._size;
  38852. },
  38853. set: function (value) {
  38854. if (this._actualSize.equals(value)) {
  38855. return;
  38856. }
  38857. this._actualSize = value;
  38858. },
  38859. enumerable: true,
  38860. configurable: true
  38861. });
  38862. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  38863. get: function () {
  38864. return this._zOrder || (1 - this._hierarchyDepthOffset);
  38865. },
  38866. enumerable: true,
  38867. configurable: true
  38868. });
  38869. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  38870. /**
  38871. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  38872. * The Primitive's size won't be less than specified.
  38873. * The default value depends of the Primitive type
  38874. */
  38875. get: function () {
  38876. return this._minSize;
  38877. },
  38878. set: function (value) {
  38879. if (this._minSize && value && this._minSize.equals(value)) {
  38880. return;
  38881. }
  38882. this._minSize = value;
  38883. this._parentLayoutDirty();
  38884. },
  38885. enumerable: true,
  38886. configurable: true
  38887. });
  38888. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  38889. /**
  38890. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  38891. * The Primitive's size won't be more than specified.
  38892. * The default value depends of the Primitive type
  38893. */
  38894. get: function () {
  38895. return this._maxSize;
  38896. },
  38897. set: function (value) {
  38898. if (this._maxSize && value && this._maxSize.equals(value)) {
  38899. return;
  38900. }
  38901. this._maxSize = value;
  38902. this._parentLayoutDirty();
  38903. },
  38904. enumerable: true,
  38905. configurable: true
  38906. });
  38907. Object.defineProperty(Prim2DBase.prototype, "origin", {
  38908. /**
  38909. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  38910. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  38911. * For instance:
  38912. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  38913. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  38914. * 0,1 means the center is top/left
  38915. * @returns The normalized center.
  38916. */
  38917. get: function () {
  38918. return this._origin;
  38919. },
  38920. set: function (value) {
  38921. this._origin = value;
  38922. },
  38923. enumerable: true,
  38924. configurable: true
  38925. });
  38926. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  38927. get: function () {
  38928. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  38929. },
  38930. set: function (value) {
  38931. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  38932. },
  38933. enumerable: true,
  38934. configurable: true
  38935. });
  38936. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  38937. get: function () {
  38938. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  38939. },
  38940. set: function (value) {
  38941. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  38942. },
  38943. enumerable: true,
  38944. configurable: true
  38945. });
  38946. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  38947. get: function () {
  38948. return this._zOrder;
  38949. },
  38950. set: function (value) {
  38951. this._zOrder = value;
  38952. this.onZOrderChanged();
  38953. },
  38954. enumerable: true,
  38955. configurable: true
  38956. });
  38957. Object.defineProperty(Prim2DBase.prototype, "margin", {
  38958. get: function () {
  38959. var _this = this;
  38960. if (!this._margin) {
  38961. this._margin = new PrimitiveThickness(function () {
  38962. if (!_this.parent) {
  38963. return null;
  38964. }
  38965. return _this.parent.margin;
  38966. }, function () { return _this._positioningDirty(); });
  38967. }
  38968. return this._margin;
  38969. },
  38970. enumerable: true,
  38971. configurable: true
  38972. });
  38973. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  38974. get: function () {
  38975. return (this._margin !== null) || (this._marginAlignment !== null);
  38976. },
  38977. enumerable: true,
  38978. configurable: true
  38979. });
  38980. Object.defineProperty(Prim2DBase.prototype, "padding", {
  38981. get: function () {
  38982. var _this = this;
  38983. if (!this._padding) {
  38984. this._padding = new PrimitiveThickness(function () {
  38985. if (!_this.parent) {
  38986. return null;
  38987. }
  38988. return _this.parent.padding;
  38989. }, function () { return _this._positioningDirty(); });
  38990. }
  38991. return this._padding;
  38992. },
  38993. enumerable: true,
  38994. configurable: true
  38995. });
  38996. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  38997. get: function () {
  38998. return this._padding !== null;
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  39004. get: function () {
  39005. var _this = this;
  39006. if (!this._marginAlignment) {
  39007. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  39008. }
  39009. return this._marginAlignment;
  39010. },
  39011. enumerable: true,
  39012. configurable: true
  39013. });
  39014. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  39015. /**
  39016. * Get/set the layout engine to use for this primitive.
  39017. * The default layout engine is the CanvasLayoutEngine.
  39018. */
  39019. get: function () {
  39020. if (!this._layoutEngine) {
  39021. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39022. }
  39023. return this._layoutEngine;
  39024. },
  39025. set: function (value) {
  39026. if (this._layoutEngine === value) {
  39027. return;
  39028. }
  39029. this._changeLayoutEngine(value);
  39030. },
  39031. enumerable: true,
  39032. configurable: true
  39033. });
  39034. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  39035. /**
  39036. * Get/set the layout are of this primitive.
  39037. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  39038. * The setter should only be called by a Layout Engine class.
  39039. */
  39040. get: function () {
  39041. return this._layoutArea;
  39042. },
  39043. set: function (val) {
  39044. if (this._layoutArea.equals(val)) {
  39045. return;
  39046. }
  39047. this._positioningDirty();
  39048. this._layoutArea = val;
  39049. },
  39050. enumerable: true,
  39051. configurable: true
  39052. });
  39053. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  39054. /**
  39055. * Get/set the layout area position (relative to the parent primitive).
  39056. * The setter should only be called by a Layout Engine class.
  39057. */
  39058. get: function () {
  39059. return this._layoutAreaPos;
  39060. },
  39061. set: function (val) {
  39062. if (this._layoutAreaPos.equals(val)) {
  39063. return;
  39064. }
  39065. this._positioningDirty();
  39066. this._layoutAreaPos = val;
  39067. },
  39068. enumerable: true,
  39069. configurable: true
  39070. });
  39071. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  39072. /**
  39073. * Define if the Primitive can be subject to intersection test or not (default is true)
  39074. */
  39075. get: function () {
  39076. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  39077. },
  39078. set: function (value) {
  39079. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  39080. },
  39081. enumerable: true,
  39082. configurable: true
  39083. });
  39084. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  39085. /**
  39086. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  39087. */
  39088. get: function () {
  39089. return this._hierarchyDepth;
  39090. },
  39091. enumerable: true,
  39092. configurable: true
  39093. });
  39094. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  39095. /**
  39096. * Retrieve the Group that is responsible to render this primitive
  39097. */
  39098. get: function () {
  39099. return this._renderGroup;
  39100. },
  39101. enumerable: true,
  39102. configurable: true
  39103. });
  39104. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  39105. /**
  39106. * Get the global transformation matrix of the primitive
  39107. */
  39108. get: function () {
  39109. return this._globalTransform;
  39110. },
  39111. enumerable: true,
  39112. configurable: true
  39113. });
  39114. /**
  39115. * return the global position of the primitive, relative to its canvas
  39116. */
  39117. Prim2DBase.prototype.getGlobalPosition = function () {
  39118. var v = new BABYLON.Vector2(0, 0);
  39119. this.getGlobalPositionByRef(v);
  39120. return v;
  39121. };
  39122. /**
  39123. * return the global position of the primitive, relative to its canvas
  39124. * @param v the valid Vector2 object where the global position will be stored
  39125. */
  39126. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  39127. v.x = this.globalTransform.m[12];
  39128. v.y = this.globalTransform.m[13];
  39129. };
  39130. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  39131. /**
  39132. * Get invert of the global transformation matrix of the primitive
  39133. */
  39134. get: function () {
  39135. return this._invGlobalTransform;
  39136. },
  39137. enumerable: true,
  39138. configurable: true
  39139. });
  39140. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  39141. /**
  39142. * Get the local transformation of the primitive
  39143. */
  39144. get: function () {
  39145. this._updateLocalTransform();
  39146. return this._localTransform;
  39147. },
  39148. enumerable: true,
  39149. configurable: true
  39150. });
  39151. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  39152. /**
  39153. * Get the boundingInfo associated to the primitive and its children.
  39154. * The value is supposed to be always up to date
  39155. */
  39156. get: function () {
  39157. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39158. this._boundingInfo = this.levelBoundingInfo.clone();
  39159. var bi = this._boundingInfo;
  39160. var tps = new BABYLON.BoundingInfo2D();
  39161. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39162. var curChild = _a[_i];
  39163. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  39164. bi.unionToRef(tps, bi);
  39165. }
  39166. this._boundingSize = BABYLON.Size.Zero();
  39167. var m = this._boundingInfo.max();
  39168. this._boundingSize = new BABYLON.Size((!this._size || this._size.width == null) ? Math.ceil(m.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(m.y) : this._size.height);
  39169. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  39170. }
  39171. return this._boundingInfo;
  39172. },
  39173. enumerable: true,
  39174. configurable: true
  39175. });
  39176. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  39177. /**
  39178. * Determine if the size is automatically computed or fixed because manually specified.
  39179. * Use the actualSize property to get the final/real size of the primitive
  39180. * @returns true if the size is automatically computed, false if it were manually specified.
  39181. */
  39182. get: function () {
  39183. return this._size == null;
  39184. },
  39185. enumerable: true,
  39186. configurable: true
  39187. });
  39188. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  39189. /**
  39190. * Determine if the position is automatically computed or fixed because manually specified.
  39191. * Use the actualPosition property to get the final/real position of the primitive
  39192. * @returns true if the position is automatically computed, false if it were manually specified.
  39193. */
  39194. get: function () {
  39195. return this._position == null;
  39196. },
  39197. enumerable: true,
  39198. configurable: true
  39199. });
  39200. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  39201. /**
  39202. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  39203. */
  39204. get: function () {
  39205. return this._pointerEventObservable;
  39206. },
  39207. enumerable: true,
  39208. configurable: true
  39209. });
  39210. Prim2DBase.prototype.findById = function (id) {
  39211. if (this._id === id) {
  39212. return this;
  39213. }
  39214. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39215. var child = _a[_i];
  39216. var r = child.findById(id);
  39217. if (r != null) {
  39218. return r;
  39219. }
  39220. }
  39221. };
  39222. Prim2DBase.prototype.onZOrderChanged = function () {
  39223. };
  39224. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  39225. return false;
  39226. };
  39227. /**
  39228. * Capture all the Events of the given PointerId for this primitive.
  39229. * Don't forget to call releasePointerEventsCapture when done.
  39230. * @param pointerId the Id of the pointer to capture the events from.
  39231. */
  39232. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  39233. return this.owner._setPointerCapture(pointerId, this);
  39234. };
  39235. /**
  39236. * Release a captured pointer made with setPointerEventCapture.
  39237. * @param pointerId the Id of the pointer to release the capture from.
  39238. */
  39239. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  39240. return this.owner._releasePointerCapture(pointerId, this);
  39241. };
  39242. /**
  39243. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  39244. * @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.
  39245. */
  39246. Prim2DBase.prototype.intersect = function (intersectInfo) {
  39247. if (!intersectInfo) {
  39248. return false;
  39249. }
  39250. // If this is null it means this method is call for the first level, initialize stuffs
  39251. var firstLevel = !intersectInfo._globalPickPosition;
  39252. if (firstLevel) {
  39253. // 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).
  39254. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  39255. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  39256. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  39257. intersectInfo.intersectedPrimitives = new Array();
  39258. intersectInfo.topMostIntersectedPrimitive = null;
  39259. }
  39260. if (!intersectInfo.intersectHidden && !this.isVisible) {
  39261. return false;
  39262. }
  39263. // Fast rejection test with boundingInfo
  39264. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  39265. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  39266. intersectInfo._exit(firstLevel);
  39267. return false;
  39268. }
  39269. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  39270. var levelIntersectRes = false;
  39271. if (this.isPickable) {
  39272. levelIntersectRes = this.levelIntersect(intersectInfo);
  39273. if (levelIntersectRes) {
  39274. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  39275. intersectInfo.intersectedPrimitives.push(pii);
  39276. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  39277. intersectInfo.topMostIntersectedPrimitive = pii;
  39278. }
  39279. // If we must stop at the first intersection, we're done, quit!
  39280. if (intersectInfo.findFirstOnly) {
  39281. intersectInfo._exit(firstLevel);
  39282. return true;
  39283. }
  39284. }
  39285. }
  39286. // Recurse to children if needed
  39287. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  39288. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39289. var curChild = _a[_i];
  39290. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  39291. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  39292. continue;
  39293. }
  39294. // Must compute the localPickLocation for the children level
  39295. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  39296. // If we got an intersection with the child and we only need to find the first one, quit!
  39297. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  39298. intersectInfo._exit(firstLevel);
  39299. return true;
  39300. }
  39301. }
  39302. }
  39303. intersectInfo._exit(firstLevel);
  39304. return intersectInfo.isIntersected;
  39305. };
  39306. Prim2DBase.prototype.moveChild = function (child, previous) {
  39307. if (child.parent !== this) {
  39308. return false;
  39309. }
  39310. var prevOffset, nextOffset;
  39311. var childIndex = this._children.indexOf(child);
  39312. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  39313. // Move to first position
  39314. if (!previous) {
  39315. prevOffset = 1;
  39316. nextOffset = this._children[1]._siblingDepthOffset;
  39317. }
  39318. else {
  39319. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  39320. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  39321. }
  39322. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  39323. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  39324. };
  39325. Prim2DBase.prototype.addChild = function (child) {
  39326. child._parent = this;
  39327. this._boundingBoxDirty();
  39328. this._children.push(child);
  39329. this._patchHierarchyDepth(child);
  39330. };
  39331. /**
  39332. * Dispose the primitive, remove it from its parent.
  39333. */
  39334. Prim2DBase.prototype.dispose = function () {
  39335. if (!_super.prototype.dispose.call(this)) {
  39336. return false;
  39337. }
  39338. if (this._actionManager) {
  39339. this._actionManager.dispose();
  39340. this._actionManager = null;
  39341. }
  39342. // If there's a parent, remove this object from its parent list
  39343. if (this._parent) {
  39344. var i = this._parent._children.indexOf(this);
  39345. if (i !== undefined) {
  39346. this._parent._children.splice(i, 1);
  39347. }
  39348. this._parent = null;
  39349. }
  39350. // Recurse dispose to children
  39351. if (this._children) {
  39352. while (this._children.length > 0) {
  39353. this._children[this._children.length - 1].dispose();
  39354. }
  39355. }
  39356. return true;
  39357. };
  39358. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  39359. if (this._renderGroup) {
  39360. this._renderGroup._addPrimToDirtyList(this);
  39361. }
  39362. };
  39363. Prim2DBase.prototype._needPrepare = function () {
  39364. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  39365. };
  39366. Prim2DBase.prototype._prepareRender = function (context) {
  39367. this._prepareRenderPre(context);
  39368. this._prepareRenderPost(context);
  39369. };
  39370. Prim2DBase.prototype._prepareRenderPre = function (context) {
  39371. };
  39372. Prim2DBase.prototype._prepareRenderPost = function (context) {
  39373. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  39374. if (this instanceof BABYLON.Group2D) {
  39375. var self = this;
  39376. if (self.isRenderableGroup) {
  39377. return;
  39378. }
  39379. }
  39380. // Check if we need to recurse the prepare to children primitives
  39381. // - must have children
  39382. // - the global transform of this level have changed, or
  39383. // - the visible state of primitive has changed
  39384. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  39385. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  39386. this._children.forEach(function (c) {
  39387. // As usual stop the recursion if we meet a renderable group
  39388. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  39389. c._prepareRender(context);
  39390. }
  39391. });
  39392. }
  39393. // Finally reset the dirty flags as we've processed everything
  39394. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39395. this._instanceDirtyFlags = 0;
  39396. };
  39397. Prim2DBase.prototype._canvasPreInit = function (settings) {
  39398. };
  39399. Prim2DBase.CheckParent = function (parent) {
  39400. //if (!Prim2DBase._isCanvasInit && !parent) {
  39401. // 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)");
  39402. //}
  39403. };
  39404. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  39405. for (var _i = 0; _i < list.length; _i++) {
  39406. var cur = list[_i];
  39407. cur.updateCachedStates(recurse);
  39408. }
  39409. };
  39410. Prim2DBase.prototype._parentLayoutDirty = function () {
  39411. if (!this._parent || this._parent.isDisposed) {
  39412. return;
  39413. }
  39414. this._parent._setLayoutDirty();
  39415. };
  39416. Prim2DBase.prototype._setLayoutDirty = function () {
  39417. if (!this.isDirty) {
  39418. this.onPrimBecomesDirty();
  39419. }
  39420. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39421. };
  39422. Prim2DBase.prototype._checkPositionChange = function () {
  39423. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  39424. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  39425. return false;
  39426. }
  39427. return true;
  39428. };
  39429. Prim2DBase.prototype._positioningDirty = function () {
  39430. if (!this.isDirty) {
  39431. this.onPrimBecomesDirty();
  39432. }
  39433. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39434. };
  39435. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  39436. this._layoutEngine = engine;
  39437. };
  39438. Prim2DBase.prototype._updateLocalTransform = function () {
  39439. var parentMarginOffsetChanged = false;
  39440. var parentMarginOffset = null;
  39441. if (this._parent) {
  39442. parentMarginOffset = this._parent._marginOffset;
  39443. parentMarginOffsetChanged = !parentMarginOffset.equals(this._parentMargingOffset);
  39444. this._parentMargingOffset.copyFrom(parentMarginOffset);
  39445. }
  39446. else {
  39447. parentMarginOffset = Prim2DBase._v0;
  39448. }
  39449. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  39450. if (parentMarginOffsetChanged || this.checkPropertiesDirty(tflags)) {
  39451. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  39452. var local;
  39453. if (this._origin.x === 0 && this._origin.y === 0) {
  39454. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(this.actualPosition.x + parentMarginOffset.x, this.actualPosition.y + parentMarginOffset.y, 0));
  39455. this._localTransform = local;
  39456. }
  39457. else {
  39458. // -Origin offset
  39459. var as = this.actualSize;
  39460. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  39461. // -Origin * rotation
  39462. rot.toRotationMatrix(Prim2DBase._t1);
  39463. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  39464. // -Origin * rotation * scale
  39465. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  39466. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  39467. // -Origin * rotation * scale * (Origin + Position + Parent Margin Offset)
  39468. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + this.actualPosition.x + parentMarginOffset.x, (as.height * this._origin.y) + this.actualPosition.y + parentMarginOffset.y, 0, Prim2DBase._t2);
  39469. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  39470. }
  39471. this.clearPropertiesDirty(tflags);
  39472. return true;
  39473. }
  39474. return false;
  39475. };
  39476. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  39477. if (this.isDisposed) {
  39478. return;
  39479. }
  39480. // Check if the parent is synced
  39481. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty))) {
  39482. this._parent.updateCachedStates(false);
  39483. }
  39484. // Update actualSize only if there' not positioning to recompute and the size changed
  39485. // Otherwise positioning will take care of it.
  39486. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39487. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && sizeDirty) {
  39488. var size = this.size;
  39489. if (size) {
  39490. if (this.size.width != null) {
  39491. this.actualSize.width = this.size.width;
  39492. }
  39493. if (this.size.height != null) {
  39494. this.actualSize.height = this.size.height;
  39495. }
  39496. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39497. }
  39498. }
  39499. // Check for layout update
  39500. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39501. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  39502. this._layoutEngine.updateLayout(this);
  39503. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39504. }
  39505. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39506. // Check for positioning update
  39507. if (!positioningComputed && (sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  39508. this._updatePositioning();
  39509. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39510. positioningComputed = true;
  39511. }
  39512. if (positioningComputed && this._parent) {
  39513. this._parentContentArea.copyFrom(this._parent.contentArea);
  39514. }
  39515. // Check if we must update this prim
  39516. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  39517. var curVisibleState = this.isVisible;
  39518. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  39519. // Detect a change of visibility
  39520. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  39521. // Get/compute the localTransform
  39522. var localDirty = this._updateLocalTransform();
  39523. // Check if there are changes in the parent that will force us to update the global matrix
  39524. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  39525. // Check if we have to update the globalTransform
  39526. if (!this._globalTransform || localDirty || parentDirty) {
  39527. var globalTransform = this._parent ? this._parent._globalTransform : null;
  39528. this._globalTransform = this._parent ? this._localTransform.multiply(globalTransform) : this._localTransform;
  39529. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  39530. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  39531. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  39532. }
  39533. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  39534. }
  39535. if (recurse) {
  39536. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39537. var child = _a[_i];
  39538. // Stop the recursion if we meet a renderable group
  39539. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  39540. }
  39541. }
  39542. };
  39543. Prim2DBase.prototype._updatePositioning = function () {
  39544. // From this point we assume that the primitive layoutArea is computed and up to date.
  39545. // We know have to :
  39546. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  39547. // 2. Determine the contentArea based on the padding property.
  39548. // 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
  39549. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  39550. if (this.actualSize.width == null) {
  39551. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  39552. }
  39553. if (this.actualSize.height == null) {
  39554. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  39555. }
  39556. }
  39557. // Apply margin
  39558. if (this._hasMargin) {
  39559. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  39560. this.actualPosition = this._marginOffset.add(this._layoutAreaPos);
  39561. if (this.size.width != null) {
  39562. this.size.width = Prim2DBase._size.width;
  39563. }
  39564. if (this.size.height != null) {
  39565. this.size.height = Prim2DBase._size.height;
  39566. }
  39567. this.actualSize.copyFrom(Prim2DBase._size.clone());
  39568. }
  39569. if (this._hasPadding) {
  39570. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39571. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39572. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39573. this.padding.compute(Prim2DBase._icArea, this._marginOffset, Prim2DBase._size);
  39574. this._marginOffset.x += Prim2DBase._icPos.x;
  39575. this._marginOffset.y += Prim2DBase._icPos.y;
  39576. this._contentArea.copyFrom(Prim2DBase._size);
  39577. }
  39578. else {
  39579. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39580. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39581. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39582. this._marginOffset.copyFrom(Prim2DBase._icPos);
  39583. this._contentArea.copyFrom(Prim2DBase._icArea);
  39584. }
  39585. };
  39586. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  39587. /**
  39588. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  39589. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  39590. */
  39591. get: function () {
  39592. // Check for positioning update
  39593. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  39594. this._updatePositioning();
  39595. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39596. }
  39597. return this._contentArea;
  39598. },
  39599. enumerable: true,
  39600. configurable: true
  39601. });
  39602. Prim2DBase.prototype._patchHierarchy = function (owner) {
  39603. this._owner = owner;
  39604. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  39605. if (this._renderGroup != null) {
  39606. return;
  39607. }
  39608. if (this instanceof BABYLON.Group2D) {
  39609. var group = this;
  39610. group.detectGroupStates();
  39611. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  39612. group.owner._registerTrackedNode(this);
  39613. }
  39614. }
  39615. if (this._parent) {
  39616. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  39617. this._parentLayoutDirty();
  39618. }
  39619. // Make sure the prim is in the dirtyList if it should be
  39620. if (this._renderGroup && this.isDirty) {
  39621. var list = this._renderGroup._renderableData._primDirtyList;
  39622. var i = list.indexOf(this);
  39623. if (i === -1) {
  39624. list.push(this);
  39625. }
  39626. }
  39627. // Recurse
  39628. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39629. var child = _a[_i];
  39630. this._patchHierarchyDepth(child);
  39631. child._patchHierarchy(owner);
  39632. }
  39633. };
  39634. Prim2DBase.prototype._patchHierarchyDepth = function (child) {
  39635. child._hierarchyDepth = this._hierarchyDepth + 1;
  39636. child._hierarchyDepthOffset = this._hierarchyDepthOffset + ((this._children.indexOf(child) + 1) * this._siblingDepthOffset);
  39637. child._siblingDepthOffset = this._siblingDepthOffset / BABYLON.Canvas2D.hierarchyLevelMaxSiblingCount;
  39638. };
  39639. /**
  39640. * This method is used to alter the contentArea of the Primitive before margin is applied.
  39641. * 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.
  39642. * @param primSize the current size of the primitive
  39643. * @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!
  39644. * @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!
  39645. */
  39646. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  39647. initialContentArea.width = primSize.width;
  39648. initialContentArea.height = primSize.height;
  39649. initialContentPosition.x = initialContentPosition.y = 0;
  39650. };
  39651. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  39652. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  39653. Prim2DBase.boundinbBoxReentrency = false;
  39654. Prim2DBase.nullSize = BABYLON.Size.Zero();
  39655. Prim2DBase._isCanvasInit = false;
  39656. Prim2DBase._t0 = new BABYLON.Matrix();
  39657. Prim2DBase._t1 = new BABYLON.Matrix();
  39658. Prim2DBase._t2 = new BABYLON.Matrix();
  39659. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  39660. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  39661. Prim2DBase._icArea = BABYLON.Size.Zero();
  39662. Prim2DBase._size = BABYLON.Size.Zero();
  39663. __decorate([
  39664. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, true)
  39665. ], Prim2DBase.prototype, "actualPosition", null);
  39666. __decorate([
  39667. BABYLON.dynamicLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  39668. ], Prim2DBase.prototype, "position", null);
  39669. __decorate([
  39670. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  39671. ], Prim2DBase.prototype, "size", null);
  39672. __decorate([
  39673. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  39674. ], Prim2DBase.prototype, "rotation", null);
  39675. __decorate([
  39676. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  39677. ], Prim2DBase.prototype, "scale", null);
  39678. __decorate([
  39679. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  39680. ], Prim2DBase.prototype, "origin", null);
  39681. __decorate([
  39682. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  39683. ], Prim2DBase.prototype, "levelVisible", null);
  39684. __decorate([
  39685. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  39686. ], Prim2DBase.prototype, "isVisible", null);
  39687. __decorate([
  39688. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  39689. ], Prim2DBase.prototype, "zOrder", null);
  39690. __decorate([
  39691. BABYLON.dynamicLevelProperty(9, function (pi) { return Prim2DBase.marginProperty = pi; })
  39692. ], Prim2DBase.prototype, "margin", null);
  39693. __decorate([
  39694. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.paddingProperty = pi; })
  39695. ], Prim2DBase.prototype, "padding", null);
  39696. __decorate([
  39697. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  39698. ], Prim2DBase.prototype, "marginAlignment", null);
  39699. Prim2DBase = __decorate([
  39700. BABYLON.className("Prim2DBase")
  39701. ], Prim2DBase);
  39702. return Prim2DBase;
  39703. })(BABYLON.SmartPropertyPrim);
  39704. BABYLON.Prim2DBase = Prim2DBase;
  39705. })(BABYLON || (BABYLON = {}));
  39706. var BABYLON;
  39707. (function (BABYLON) {
  39708. var GroupInstanceInfo = (function () {
  39709. function GroupInstanceInfo(owner, mrc, partCount) {
  39710. this._partCount = partCount;
  39711. this.owner = owner;
  39712. this.modelRenderCache = mrc;
  39713. this.modelRenderCache.addRef();
  39714. this.partIndexFromId = new BABYLON.StringDictionary();
  39715. this._usedShaderCategories = new Array(partCount);
  39716. this._strides = new Array(partCount);
  39717. this._opaqueData = null;
  39718. this._alphaTestData = null;
  39719. this._transparentData = null;
  39720. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  39721. }
  39722. GroupInstanceInfo.prototype.dispose = function () {
  39723. if (this._isDisposed) {
  39724. return false;
  39725. }
  39726. if (this.modelRenderCache) {
  39727. this.modelRenderCache.dispose();
  39728. }
  39729. var engine = this.owner.owner.engine;
  39730. if (this.opaqueData) {
  39731. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  39732. this.opaqueData = null;
  39733. }
  39734. this.partIndexFromId = null;
  39735. this._isDisposed = true;
  39736. return true;
  39737. };
  39738. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  39739. get: function () {
  39740. return this._opaqueData != null;
  39741. },
  39742. enumerable: true,
  39743. configurable: true
  39744. });
  39745. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  39746. get: function () {
  39747. return this._alphaTestData != null;
  39748. },
  39749. enumerable: true,
  39750. configurable: true
  39751. });
  39752. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  39753. get: function () {
  39754. return this._transparentData != null;
  39755. },
  39756. enumerable: true,
  39757. configurable: true
  39758. });
  39759. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  39760. get: function () {
  39761. if (!this._opaqueData) {
  39762. this._opaqueData = new Array(this._partCount);
  39763. for (var i = 0; i < this._partCount; i++) {
  39764. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  39765. }
  39766. }
  39767. return this._opaqueData;
  39768. },
  39769. enumerable: true,
  39770. configurable: true
  39771. });
  39772. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  39773. get: function () {
  39774. if (!this._alphaTestData) {
  39775. this._alphaTestData = new Array(this._partCount);
  39776. for (var i = 0; i < this._partCount; i++) {
  39777. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  39778. }
  39779. }
  39780. return this._alphaTestData;
  39781. },
  39782. enumerable: true,
  39783. configurable: true
  39784. });
  39785. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  39786. get: function () {
  39787. if (!this._transparentData) {
  39788. this._transparentData = new Array(this._partCount);
  39789. for (var i = 0; i < this._partCount; i++) {
  39790. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  39791. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  39792. }
  39793. }
  39794. return this._transparentData;
  39795. },
  39796. enumerable: true,
  39797. configurable: true
  39798. });
  39799. GroupInstanceInfo.prototype.sortTransparentData = function () {
  39800. if (!this.transparentOrderDirty) {
  39801. return;
  39802. }
  39803. for (var i = 0; i < this._transparentData.length; i++) {
  39804. var td = this._transparentData[i];
  39805. td._partData.sort();
  39806. }
  39807. this.transparentOrderDirty = false;
  39808. };
  39809. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  39810. get: function () {
  39811. return this._usedShaderCategories;
  39812. },
  39813. enumerable: true,
  39814. configurable: true
  39815. });
  39816. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  39817. get: function () {
  39818. return this._strides;
  39819. },
  39820. enumerable: true,
  39821. configurable: true
  39822. });
  39823. return GroupInstanceInfo;
  39824. })();
  39825. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  39826. var TransparentSegment = (function () {
  39827. function TransparentSegment() {
  39828. }
  39829. return TransparentSegment;
  39830. })();
  39831. BABYLON.TransparentSegment = TransparentSegment;
  39832. var GroupInfoPartData = (function () {
  39833. function GroupInfoPartData(stride) {
  39834. this._partData = null;
  39835. this._partBuffer = null;
  39836. this._partBufferSize = 0;
  39837. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  39838. this._isDisposed = false;
  39839. }
  39840. GroupInfoPartData.prototype.dispose = function (engine) {
  39841. if (this._isDisposed) {
  39842. return false;
  39843. }
  39844. if (this._partBuffer) {
  39845. engine._releaseBuffer(this._partBuffer);
  39846. this._partBuffer = null;
  39847. }
  39848. this._partData = null;
  39849. this._isDisposed = true;
  39850. };
  39851. return GroupInfoPartData;
  39852. })();
  39853. BABYLON.GroupInfoPartData = GroupInfoPartData;
  39854. var TransparentGroupInfoPartData = (function (_super) {
  39855. __extends(TransparentGroupInfoPartData, _super);
  39856. function TransparentGroupInfoPartData(stride, zoff) {
  39857. _super.call(this, stride);
  39858. this._partData.compareValueOffset = zoff;
  39859. this._partData.sortingAscending = false;
  39860. }
  39861. return TransparentGroupInfoPartData;
  39862. })(GroupInfoPartData);
  39863. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  39864. var ModelRenderCache = (function () {
  39865. function ModelRenderCache(engine, modelKey) {
  39866. this._engine = engine;
  39867. this._modelKey = modelKey;
  39868. this._nextKey = 1;
  39869. this._refCounter = 1;
  39870. this._instancesData = new BABYLON.StringDictionary();
  39871. this._partData = null;
  39872. }
  39873. ModelRenderCache.prototype.dispose = function () {
  39874. if (--this._refCounter !== 0) {
  39875. return false;
  39876. }
  39877. // Remove the Model Render Cache from the global dictionary
  39878. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  39879. if (edata) {
  39880. edata.DisposeModelRenderCache(this);
  39881. }
  39882. return true;
  39883. };
  39884. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  39885. get: function () {
  39886. return this._refCounter <= 0;
  39887. },
  39888. enumerable: true,
  39889. configurable: true
  39890. });
  39891. ModelRenderCache.prototype.addRef = function () {
  39892. return ++this._refCounter;
  39893. };
  39894. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  39895. get: function () {
  39896. return this._modelKey;
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. /**
  39902. * Render the model instances
  39903. * @param instanceInfo
  39904. * @param context
  39905. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  39906. */
  39907. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  39908. return true;
  39909. };
  39910. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  39911. var key = this._nextKey.toString();
  39912. if (!this._instancesData.add(key, data)) {
  39913. throw Error("Key: " + key + " is already allocated");
  39914. }
  39915. ++this._nextKey;
  39916. return key;
  39917. };
  39918. ModelRenderCache.prototype.removeInstanceData = function (key) {
  39919. this._instancesData.remove(key);
  39920. };
  39921. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  39922. for (var i = 0; i < this._partData.length; i++) {
  39923. if (this._partData[i]._partId === partId) {
  39924. return i;
  39925. }
  39926. }
  39927. return null;
  39928. };
  39929. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  39930. var i = this.getPartIndexFromId(partId);
  39931. if (i === null) {
  39932. return null;
  39933. }
  39934. var ci = this._partsClassInfo[i];
  39935. var categories = this._partData[i]._partUsedCategories;
  39936. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  39937. return res;
  39938. };
  39939. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  39940. var pd = this._partData[partIndex];
  39941. var offset = (pd._partDataStride / 4) * elementCount;
  39942. var pci = this._partsClassInfo[partIndex];
  39943. var self = this;
  39944. pci.fullContent.forEach(function (k, v) {
  39945. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  39946. switch (v.dataType) {
  39947. case 4 /* float */:
  39948. {
  39949. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39950. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  39951. break;
  39952. }
  39953. case 0 /* Vector2 */:
  39954. {
  39955. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39956. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  39957. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  39958. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  39959. break;
  39960. }
  39961. case 5 /* Color3 */:
  39962. case 1 /* Vector3 */:
  39963. {
  39964. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39965. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  39966. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  39967. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  39968. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  39969. break;
  39970. }
  39971. case 6 /* Color4 */:
  39972. case 2 /* Vector4 */:
  39973. {
  39974. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  39975. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  39976. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  39977. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  39978. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  39979. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  39980. break;
  39981. }
  39982. default:
  39983. }
  39984. }
  39985. });
  39986. };
  39987. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  39988. // let i = this.getPartIndexFromId(partId);
  39989. // if (i === null) {
  39990. // return null;
  39991. // }
  39992. // let pci = this._partsClassInfo[i];
  39993. // pci.fullContent.forEach((k, v) => {
  39994. // if (uniforms.indexOf(v.attributeName) !== -1) {
  39995. // v.uniformLocation = effect.getUniform(v.attributeName);
  39996. // }
  39997. // });
  39998. //}
  39999. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  40000. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  40001. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  40002. return ModelRenderCache;
  40003. })();
  40004. BABYLON.ModelRenderCache = ModelRenderCache;
  40005. var ModelRenderCachePartData = (function () {
  40006. function ModelRenderCachePartData() {
  40007. }
  40008. return ModelRenderCachePartData;
  40009. })();
  40010. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  40011. })(BABYLON || (BABYLON = {}));
  40012. var BABYLON;
  40013. (function (BABYLON) {
  40014. var InstanceClassInfo = (function () {
  40015. function InstanceClassInfo(base) {
  40016. this._baseInfo = base;
  40017. this._nextOffset = new BABYLON.StringDictionary();
  40018. this._attributes = new Array();
  40019. }
  40020. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  40021. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  40022. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  40023. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  40024. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  40025. if (push) {
  40026. this._attributes.push(propInfo);
  40027. }
  40028. };
  40029. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  40030. var catInline = ";" + categories.join(";") + ";";
  40031. var res = new Array();
  40032. var curInfo = this;
  40033. while (curInfo) {
  40034. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40035. var attrib = _a[_i];
  40036. // 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
  40037. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40038. var index = effect.getAttributeLocationByName(attrib.attributeName);
  40039. var iai = new BABYLON.InstancingAttributeInfo();
  40040. iai.index = index;
  40041. 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)
  40042. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  40043. iai.attributeName = attrib.attributeName;
  40044. res.push(iai);
  40045. }
  40046. }
  40047. curInfo = curInfo._baseInfo;
  40048. }
  40049. return res;
  40050. };
  40051. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  40052. var res = new Array();
  40053. var curInfo = this;
  40054. while (curInfo) {
  40055. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40056. var attrib = _a[_i];
  40057. // 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
  40058. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40059. res.push(attrib.attributeName);
  40060. }
  40061. }
  40062. curInfo = curInfo._baseInfo;
  40063. }
  40064. return res;
  40065. };
  40066. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  40067. var curOffset = 0;
  40068. var curBase = this._baseInfo;
  40069. while (curBase) {
  40070. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  40071. curBase = curBase._baseInfo;
  40072. }
  40073. return curOffset;
  40074. };
  40075. return InstanceClassInfo;
  40076. })();
  40077. BABYLON.InstanceClassInfo = InstanceClassInfo;
  40078. var InstancePropInfo = (function () {
  40079. function InstancePropInfo() {
  40080. this.instanceOffset = new BABYLON.StringDictionary();
  40081. }
  40082. InstancePropInfo.prototype.setSize = function (val) {
  40083. if (val instanceof BABYLON.Vector2) {
  40084. this.size = 8;
  40085. this.dataType = 0 /* Vector2 */;
  40086. return;
  40087. }
  40088. if (val instanceof BABYLON.Vector3) {
  40089. this.size = 12;
  40090. this.dataType = 1 /* Vector3 */;
  40091. return;
  40092. }
  40093. if (val instanceof BABYLON.Vector4) {
  40094. this.size = 16;
  40095. this.dataType = 2 /* Vector4 */;
  40096. return;
  40097. }
  40098. if (val instanceof BABYLON.Matrix) {
  40099. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  40100. }
  40101. if (typeof (val) === "number") {
  40102. this.size = 4;
  40103. this.dataType = 4 /* float */;
  40104. return;
  40105. }
  40106. if (val instanceof BABYLON.Color3) {
  40107. this.size = 12;
  40108. this.dataType = 5 /* Color3 */;
  40109. return;
  40110. }
  40111. if (val instanceof BABYLON.Color4) {
  40112. this.size = 16;
  40113. this.dataType = 6 /* Color4 */;
  40114. return;
  40115. }
  40116. if (val instanceof BABYLON.Size) {
  40117. this.size = 8;
  40118. this.dataType = 7 /* Size */;
  40119. return;
  40120. }
  40121. return;
  40122. };
  40123. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  40124. switch (this.dataType) {
  40125. case 0 /* Vector2 */:
  40126. {
  40127. var v = val;
  40128. array[offset + 0] = v.x;
  40129. array[offset + 1] = v.y;
  40130. break;
  40131. }
  40132. case 1 /* Vector3 */:
  40133. {
  40134. var v = val;
  40135. array[offset + 0] = v.x;
  40136. array[offset + 1] = v.y;
  40137. array[offset + 2] = v.z;
  40138. break;
  40139. }
  40140. case 2 /* Vector4 */:
  40141. {
  40142. var v = val;
  40143. array[offset + 0] = v.x;
  40144. array[offset + 1] = v.y;
  40145. array[offset + 2] = v.z;
  40146. array[offset + 3] = v.w;
  40147. break;
  40148. }
  40149. case 5 /* Color3 */:
  40150. {
  40151. var v = val;
  40152. array[offset + 0] = v.r;
  40153. array[offset + 1] = v.g;
  40154. array[offset + 2] = v.b;
  40155. break;
  40156. }
  40157. case 6 /* Color4 */:
  40158. {
  40159. var v = val;
  40160. array[offset + 0] = v.r;
  40161. array[offset + 1] = v.g;
  40162. array[offset + 2] = v.b;
  40163. array[offset + 3] = v.a;
  40164. break;
  40165. }
  40166. case 4 /* float */:
  40167. {
  40168. var v = val;
  40169. array[offset] = v;
  40170. break;
  40171. }
  40172. case 3 /* Matrix */:
  40173. {
  40174. var v = val;
  40175. for (var i = 0; i < 16; i++) {
  40176. array[offset + i] = v.m[i];
  40177. }
  40178. break;
  40179. }
  40180. case 7 /* Size */:
  40181. {
  40182. var s = val;
  40183. array[offset + 0] = s.width;
  40184. array[offset + 1] = s.height;
  40185. break;
  40186. }
  40187. }
  40188. };
  40189. return InstancePropInfo;
  40190. })();
  40191. BABYLON.InstancePropInfo = InstancePropInfo;
  40192. function instanceData(category, shaderAttributeName) {
  40193. return function (target, propName, descriptor) {
  40194. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  40195. var node = dic.getLevelOf(target);
  40196. var instanceDataName = propName;
  40197. shaderAttributeName = shaderAttributeName || instanceDataName;
  40198. var info = node.levelContent.get(instanceDataName);
  40199. if (info) {
  40200. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  40201. }
  40202. info = new InstancePropInfo();
  40203. info.attributeName = shaderAttributeName;
  40204. info.category = category || null;
  40205. if (info.category) {
  40206. info.delimitedCategory = ";" + info.category + ";";
  40207. }
  40208. node.levelContent.add(instanceDataName, info);
  40209. descriptor.get = function () {
  40210. return null;
  40211. };
  40212. descriptor.set = function (val) {
  40213. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  40214. // Quit if it's the case, otherwise we could overwrite data somewhere...
  40215. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  40216. return;
  40217. }
  40218. if (!info.size) {
  40219. info.setSize(val);
  40220. node.classContent.mapProperty(info, true);
  40221. }
  40222. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  40223. node.classContent.mapProperty(info, false);
  40224. }
  40225. var obj = this;
  40226. if (obj.dataBuffer && obj.dataElements) {
  40227. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  40228. info.writeData(obj.dataBuffer.buffer, offset, val);
  40229. }
  40230. };
  40231. };
  40232. }
  40233. BABYLON.instanceData = instanceData;
  40234. var InstanceDataBase = (function () {
  40235. function InstanceDataBase(partId, dataElementCount) {
  40236. this.id = partId;
  40237. this.curElement = 0;
  40238. this.dataElementCount = dataElementCount;
  40239. }
  40240. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  40241. get: function () {
  40242. return null;
  40243. },
  40244. enumerable: true,
  40245. configurable: true
  40246. });
  40247. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  40248. get: function () {
  40249. return null;
  40250. },
  40251. enumerable: true,
  40252. configurable: true
  40253. });
  40254. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  40255. get: function () {
  40256. return null;
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. InstanceDataBase.prototype.getClassTreeInfo = function () {
  40262. if (!this.typeInfo) {
  40263. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  40264. }
  40265. return this.typeInfo;
  40266. };
  40267. InstanceDataBase.prototype.allocElements = function () {
  40268. if (!this.dataBuffer) {
  40269. return;
  40270. }
  40271. var res = new Array(this.dataElementCount);
  40272. for (var i = 0; i < this.dataElementCount; i++) {
  40273. res[i] = this.dataBuffer.allocElement();
  40274. }
  40275. this.dataElements = res;
  40276. };
  40277. InstanceDataBase.prototype.freeElements = function () {
  40278. if (!this.dataElements) {
  40279. return;
  40280. }
  40281. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  40282. var ei = _a[_i];
  40283. this.dataBuffer.freeElement(ei);
  40284. }
  40285. this.dataElements = null;
  40286. };
  40287. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  40288. get: function () {
  40289. return this._dataElementCount;
  40290. },
  40291. set: function (value) {
  40292. if (value === this._dataElementCount) {
  40293. return;
  40294. }
  40295. this.freeElements();
  40296. this._dataElementCount = value;
  40297. this.allocElements();
  40298. },
  40299. enumerable: true,
  40300. configurable: true
  40301. });
  40302. __decorate([
  40303. instanceData()
  40304. ], InstanceDataBase.prototype, "zBias", null);
  40305. __decorate([
  40306. instanceData()
  40307. ], InstanceDataBase.prototype, "transformX", null);
  40308. __decorate([
  40309. instanceData()
  40310. ], InstanceDataBase.prototype, "transformY", null);
  40311. return InstanceDataBase;
  40312. })();
  40313. BABYLON.InstanceDataBase = InstanceDataBase;
  40314. var RenderablePrim2D = (function (_super) {
  40315. __extends(RenderablePrim2D, _super);
  40316. function RenderablePrim2D(settings) {
  40317. _super.call(this, settings);
  40318. this._isTransparent = false;
  40319. this._isAlphaTest = false;
  40320. this._transparentPrimitiveInfo = null;
  40321. }
  40322. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  40323. get: function () {
  40324. return this._isAlphaTest;
  40325. },
  40326. set: function (value) {
  40327. this._isAlphaTest = value;
  40328. },
  40329. enumerable: true,
  40330. configurable: true
  40331. });
  40332. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  40333. get: function () {
  40334. return this._isTransparent;
  40335. },
  40336. set: function (value) {
  40337. this._isTransparent = value;
  40338. },
  40339. enumerable: true,
  40340. configurable: true
  40341. });
  40342. /**
  40343. * Dispose the primitive and its resources, remove it from its parent
  40344. */
  40345. RenderablePrim2D.prototype.dispose = function () {
  40346. if (!_super.prototype.dispose.call(this)) {
  40347. return false;
  40348. }
  40349. if (this._transparentPrimitiveInfo) {
  40350. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  40351. this._transparentPrimitiveInfo = null;
  40352. }
  40353. if (this._modelRenderInstanceID) {
  40354. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  40355. this._modelRenderInstanceID = null;
  40356. }
  40357. if (this._modelRenderCache) {
  40358. this._modelRenderCache.dispose();
  40359. this._modelRenderCache = null;
  40360. }
  40361. if (this._instanceDataParts) {
  40362. this._instanceDataParts.forEach(function (p) {
  40363. p.freeElements();
  40364. });
  40365. this._instanceDataParts = null;
  40366. }
  40367. return true;
  40368. };
  40369. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  40370. _super.prototype._prepareRenderPre.call(this, context);
  40371. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  40372. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  40373. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  40374. this._modelRenderInstanceID = null;
  40375. }
  40376. // Need to create the model?
  40377. var setupModelRenderCache = false;
  40378. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  40379. setupModelRenderCache = this._createModelRenderCache();
  40380. }
  40381. var gii = null;
  40382. var newInstance = false;
  40383. // Need to create the instance data parts?
  40384. if (!this._modelRenderInstanceID) {
  40385. // Yes, flag it for later, more processing will have to be done
  40386. newInstance = true;
  40387. gii = this._createModelDataParts();
  40388. }
  40389. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  40390. if (setupModelRenderCache) {
  40391. this.setupModelRenderCache(this._modelRenderCache);
  40392. }
  40393. // 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.
  40394. // 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.
  40395. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  40396. if (this.isTransparent) {
  40397. }
  40398. this._updateInstanceDataParts(gii);
  40399. }
  40400. };
  40401. RenderablePrim2D.prototype._createModelRenderCache = function () {
  40402. var _this = this;
  40403. var setupModelRenderCache = false;
  40404. if (this._modelRenderCache) {
  40405. this._modelRenderCache.dispose();
  40406. }
  40407. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  40408. var mrc = _this.createModelRenderCache(key);
  40409. setupModelRenderCache = true;
  40410. return mrc;
  40411. });
  40412. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  40413. // if this is still false it means the MRC already exists, so we add a reference to it
  40414. if (!setupModelRenderCache) {
  40415. this._modelRenderCache.addRef();
  40416. }
  40417. return setupModelRenderCache;
  40418. };
  40419. RenderablePrim2D.prototype._createModelDataParts = function () {
  40420. var _this = this;
  40421. // Create the instance data parts of the primitive and store them
  40422. var parts = this.createInstanceDataParts();
  40423. this._instanceDataParts = parts;
  40424. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  40425. if (!this._modelRenderCache._partData) {
  40426. this._setupModelRenderCache(parts);
  40427. }
  40428. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  40429. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  40430. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  40431. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  40432. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  40433. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  40434. var part = _this._instanceDataParts[j];
  40435. res.partIndexFromId.add(part.id.toString(), j);
  40436. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  40437. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  40438. }
  40439. return res;
  40440. });
  40441. // Get the GroupInfoDataPart corresponding to the render category of the part
  40442. var gipd = null;
  40443. if (this.isTransparent) {
  40444. gipd = gii.transparentData;
  40445. }
  40446. else if (this.isAlphaTest) {
  40447. gipd = gii.alphaTestData;
  40448. }
  40449. else {
  40450. gipd = gii.opaqueData;
  40451. }
  40452. // For each instance data part of the primitive, allocate the instanced element it needs for render
  40453. for (var i = 0; i < parts.length; i++) {
  40454. var part = parts[i];
  40455. part.dataBuffer = gipd[i]._partData;
  40456. part.allocElements();
  40457. }
  40458. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  40459. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  40460. return gii;
  40461. };
  40462. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  40463. var ctiArray = new Array();
  40464. this._modelRenderCache._partData = new Array();
  40465. for (var _i = 0; _i < parts.length; _i++) {
  40466. var dataPart = parts[_i];
  40467. var pd = new BABYLON.ModelRenderCachePartData();
  40468. this._modelRenderCache._partData.push(pd);
  40469. var cat = this.getUsedShaderCategories(dataPart);
  40470. var cti = dataPart.getClassTreeInfo();
  40471. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  40472. var curVisible = this.isVisible;
  40473. this.isVisible = true;
  40474. // 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.
  40475. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  40476. var joinCat = ";" + cat.join(";") + ";";
  40477. pd._partJoinedUsedCategories = joinCat;
  40478. InstanceClassInfo._CurCategories = joinCat;
  40479. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  40480. this.refreshInstanceDataPart(dataPart);
  40481. this.afterRefreshForLayoutConstruction(dataPart, obj);
  40482. this.isVisible = curVisible;
  40483. var size = 0;
  40484. cti.fullContent.forEach(function (k, v) {
  40485. if (!v.category || cat.indexOf(v.category) !== -1) {
  40486. if (v.attributeName === "zBias") {
  40487. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  40488. }
  40489. if (!v.size) {
  40490. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  40491. }
  40492. else {
  40493. size += v.size;
  40494. }
  40495. }
  40496. });
  40497. pd._partDataStride = size;
  40498. pd._partUsedCategories = cat;
  40499. pd._partId = dataPart.id;
  40500. ctiArray.push(cti);
  40501. }
  40502. this._modelRenderCache._partsClassInfo = ctiArray;
  40503. };
  40504. RenderablePrim2D.prototype.onZOrderChanged = function () {
  40505. if (this.isTransparent && this._transparentPrimitiveInfo) {
  40506. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  40507. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  40508. // Flag the transparentData dirty has will have to sort it again
  40509. gii.transparentOrderDirty = true;
  40510. }
  40511. };
  40512. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  40513. // Fetch the GroupInstanceInfo if we don't already have it
  40514. if (!gii) {
  40515. gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  40516. }
  40517. // Handle changes related to ZOffset
  40518. if (this.isTransparent) {
  40519. // Handle visibility change, which is also triggered when the primitive just got created
  40520. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged)) {
  40521. if (this.isVisible) {
  40522. if (!this._transparentPrimitiveInfo) {
  40523. // Add the primitive to the list of transparent ones in the group that render is
  40524. this._transparentPrimitiveInfo = this.renderGroup._renderableData.addNewTransparentPrimitiveInfo(this, gii);
  40525. }
  40526. }
  40527. else {
  40528. if (this._transparentPrimitiveInfo) {
  40529. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  40530. this._transparentPrimitiveInfo = null;
  40531. }
  40532. }
  40533. gii.transparentOrderDirty = true;
  40534. }
  40535. }
  40536. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  40537. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40538. var part = _a[_i];
  40539. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  40540. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) && !part.dataElements) {
  40541. part.allocElements();
  40542. }
  40543. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  40544. // Will return false if the instance should not be rendered (not visible or other any reasons)
  40545. if (!this.refreshInstanceDataPart(part)) {
  40546. // Free the data element
  40547. if (part.dataElements) {
  40548. part.freeElements();
  40549. }
  40550. }
  40551. }
  40552. this._instanceDirtyFlags = 0;
  40553. // Make the appropriate data dirty
  40554. if (this.isTransparent) {
  40555. gii.transparentDirty = true;
  40556. }
  40557. else if (this.isAlphaTest) {
  40558. gii.alphaTestDirty = true;
  40559. }
  40560. else {
  40561. gii.opaqueDirty = true;
  40562. }
  40563. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  40564. };
  40565. RenderablePrim2D.prototype._getFirstIndexInDataBuffer = function () {
  40566. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40567. var part = _a[_i];
  40568. if (part) {
  40569. return part.dataElements[0].offset / part.dataBuffer.stride;
  40570. }
  40571. }
  40572. return null;
  40573. };
  40574. RenderablePrim2D.prototype._getLastIndexInDataBuffer = function () {
  40575. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  40576. var part = _a[_i];
  40577. if (part) {
  40578. return part.dataElements[part.dataElements.length - 1].offset / part.dataBuffer.stride;
  40579. }
  40580. }
  40581. return null;
  40582. };
  40583. // This internal method is mainly used for transparency processing
  40584. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  40585. var length = this._instanceDataParts.length;
  40586. for (var i = 0; i < length; i++) {
  40587. var part = this._instanceDataParts[i];
  40588. if (part) {
  40589. var stride = part.dataBuffer.stride;
  40590. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  40591. // check if it's the last in the DFA
  40592. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  40593. return null;
  40594. }
  40595. // Return the Z of the next primitive that lies in the DFA
  40596. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  40597. }
  40598. }
  40599. return null;
  40600. };
  40601. // This internal method is mainly used for transparency processing
  40602. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  40603. var length = this._instanceDataParts.length;
  40604. for (var i = 0; i < length; i++) {
  40605. var part = this._instanceDataParts[i];
  40606. if (part) {
  40607. var stride = part.dataBuffer.stride;
  40608. var firstElementOffset = part.dataElements[0].offset;
  40609. // check if it's the first in the DFA
  40610. if (firstElementOffset === 0) {
  40611. return null;
  40612. }
  40613. // Return the Z of the previous primitive that lies in the DFA
  40614. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  40615. }
  40616. }
  40617. return null;
  40618. };
  40619. /**
  40620. * Transform a given point using the Primitive's origin setting.
  40621. * This method requires the Primitive's actualSize to be accurate
  40622. * @param p the point to transform
  40623. * @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.
  40624. * @param res an allocated Vector2 that will receive the transformed content
  40625. */
  40626. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  40627. var actualSize = this.actualSize;
  40628. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  40629. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  40630. };
  40631. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  40632. this.transformPointWithOriginByRef(p, originOffset, res);
  40633. return res;
  40634. };
  40635. /**
  40636. * Get the info for a given effect based on the dataPart metadata
  40637. * @param dataPartId partId in part list to get the info
  40638. * @param vertexBufferAttributes vertex buffer attributes to manually add
  40639. * @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
  40640. */
  40641. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  40642. if (useInstanced === void 0) { useInstanced = null; }
  40643. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  40644. if (!dataPart) {
  40645. return null;
  40646. }
  40647. var instancedArray = this.owner.supportInstancedArray;
  40648. if (useInstanced != null) {
  40649. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  40650. if (useInstanced && instancedArray === false) {
  40651. return null;
  40652. }
  40653. // Use the caller's setting
  40654. instancedArray = useInstanced;
  40655. }
  40656. var cti = dataPart.getClassTreeInfo();
  40657. var categories = this.getUsedShaderCategories(dataPart);
  40658. var att = cti.classContent.getShaderAttributes(categories);
  40659. var defines = "";
  40660. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  40661. if (instancedArray) {
  40662. defines += "#define Instanced\n";
  40663. }
  40664. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  40665. };
  40666. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  40667. get: function () {
  40668. return this._modelRenderCache;
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  40674. return null;
  40675. };
  40676. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40677. };
  40678. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  40679. return null;
  40680. };
  40681. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  40682. return [];
  40683. };
  40684. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  40685. };
  40686. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  40687. };
  40688. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  40689. if (!this.isVisible) {
  40690. return false;
  40691. }
  40692. part.isVisible = this.isVisible;
  40693. // 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)
  40694. if (part.dataElementCount === 1) {
  40695. part.curElement = 0;
  40696. this.updateInstanceDataPart(part);
  40697. }
  40698. return true;
  40699. };
  40700. /**
  40701. * Update the instanceDataBase level properties of a part
  40702. * @param part the part to update
  40703. * @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).
  40704. */
  40705. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  40706. if (positionOffset === void 0) { positionOffset = null; }
  40707. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  40708. var size = this.renderGroup.viewportSize;
  40709. var zBias = this.actualZOffset;
  40710. var offX = 0;
  40711. var offY = 0;
  40712. // If there's an offset, apply the global transformation matrix on it to get a global offset
  40713. if (positionOffset) {
  40714. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  40715. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  40716. }
  40717. // 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
  40718. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  40719. // So for X:
  40720. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  40721. // - 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].
  40722. var w = size.width;
  40723. var h = size.height;
  40724. var invZBias = 1 / zBias;
  40725. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - 1);
  40726. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - 1);
  40727. part.transformX = tx;
  40728. part.transformY = ty;
  40729. // 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)
  40730. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  40731. };
  40732. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  40733. __decorate([
  40734. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  40735. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  40736. __decorate([
  40737. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  40738. ], RenderablePrim2D.prototype, "isTransparent", null);
  40739. RenderablePrim2D = __decorate([
  40740. BABYLON.className("RenderablePrim2D")
  40741. ], RenderablePrim2D);
  40742. return RenderablePrim2D;
  40743. })(BABYLON.Prim2DBase);
  40744. BABYLON.RenderablePrim2D = RenderablePrim2D;
  40745. })(BABYLON || (BABYLON = {}));
  40746. var BABYLON;
  40747. (function (BABYLON) {
  40748. var Shape2D = (function (_super) {
  40749. __extends(Shape2D, _super);
  40750. function Shape2D(settings) {
  40751. _super.call(this, settings);
  40752. if (!settings) {
  40753. settings = {};
  40754. }
  40755. var borderBrush = null;
  40756. if (settings.border) {
  40757. if (typeof (settings.border) === "string") {
  40758. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  40759. }
  40760. else {
  40761. borderBrush = settings.border;
  40762. }
  40763. }
  40764. var fillBrush = null;
  40765. if (settings.fill) {
  40766. if (typeof (settings.fill) === "string") {
  40767. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  40768. }
  40769. else {
  40770. fillBrush = settings.fill;
  40771. }
  40772. }
  40773. this.border = borderBrush;
  40774. this.fill = fillBrush;
  40775. this.borderThickness = settings.borderThickness;
  40776. }
  40777. Object.defineProperty(Shape2D.prototype, "border", {
  40778. get: function () {
  40779. return this._border;
  40780. },
  40781. set: function (value) {
  40782. this._border = value;
  40783. this._updateTransparencyStatus();
  40784. },
  40785. enumerable: true,
  40786. configurable: true
  40787. });
  40788. Object.defineProperty(Shape2D.prototype, "fill", {
  40789. /**
  40790. * Get/set the brush to render the Fill part of the Primitive
  40791. */
  40792. get: function () {
  40793. return this._fill;
  40794. },
  40795. set: function (value) {
  40796. this._fill = value;
  40797. this._updateTransparencyStatus();
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  40803. get: function () {
  40804. return this._borderThickness;
  40805. },
  40806. set: function (value) {
  40807. this._borderThickness = value;
  40808. },
  40809. enumerable: true,
  40810. configurable: true
  40811. });
  40812. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  40813. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  40814. // Fill Part
  40815. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  40816. var fill = this.fill;
  40817. if (fill instanceof BABYLON.SolidColorBrush2D) {
  40818. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  40819. }
  40820. if (fill instanceof BABYLON.GradientColorBrush2D) {
  40821. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  40822. }
  40823. }
  40824. // Border Part
  40825. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  40826. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  40827. var border = this.border;
  40828. if (border instanceof BABYLON.SolidColorBrush2D) {
  40829. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  40830. }
  40831. if (border instanceof BABYLON.GradientColorBrush2D) {
  40832. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  40833. }
  40834. }
  40835. return cat;
  40836. };
  40837. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  40838. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40839. return false;
  40840. }
  40841. // Fill Part
  40842. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  40843. var d = part;
  40844. if (this.fill) {
  40845. var fill = this.fill;
  40846. if (fill instanceof BABYLON.SolidColorBrush2D) {
  40847. d.fillSolidColor = fill.color;
  40848. }
  40849. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  40850. d.fillGradientColor1 = fill.color1;
  40851. d.fillGradientColor2 = fill.color2;
  40852. 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));
  40853. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  40854. d.fillGradientTY = ty;
  40855. }
  40856. }
  40857. }
  40858. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  40859. var d = part;
  40860. if (this.border) {
  40861. d.borderThickness = this.borderThickness;
  40862. var border = this.border;
  40863. if (border instanceof BABYLON.SolidColorBrush2D) {
  40864. d.borderSolidColor = border.color;
  40865. }
  40866. else if (border instanceof BABYLON.GradientColorBrush2D) {
  40867. d.borderGradientColor1 = border.color1;
  40868. d.borderGradientColor2 = border.color2;
  40869. 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));
  40870. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  40871. d.borderGradientTY = ty;
  40872. }
  40873. }
  40874. }
  40875. return true;
  40876. };
  40877. Shape2D.prototype._updateTransparencyStatus = function () {
  40878. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  40879. };
  40880. Shape2D.SHAPE2D_BORDERPARTID = 1;
  40881. Shape2D.SHAPE2D_FILLPARTID = 2;
  40882. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  40883. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  40884. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  40885. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  40886. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  40887. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  40888. __decorate([
  40889. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  40890. ], Shape2D.prototype, "border", null);
  40891. __decorate([
  40892. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  40893. ], Shape2D.prototype, "fill", null);
  40894. __decorate([
  40895. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  40896. ], Shape2D.prototype, "borderThickness", null);
  40897. Shape2D = __decorate([
  40898. BABYLON.className("Shape2D")
  40899. ], Shape2D);
  40900. return Shape2D;
  40901. })(BABYLON.RenderablePrim2D);
  40902. BABYLON.Shape2D = Shape2D;
  40903. var Shape2DInstanceData = (function (_super) {
  40904. __extends(Shape2DInstanceData, _super);
  40905. function Shape2DInstanceData() {
  40906. _super.apply(this, arguments);
  40907. }
  40908. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  40909. // FILL ATTRIBUTES
  40910. get: function () {
  40911. return null;
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  40917. get: function () {
  40918. return null;
  40919. },
  40920. enumerable: true,
  40921. configurable: true
  40922. });
  40923. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  40924. get: function () {
  40925. return null;
  40926. },
  40927. enumerable: true,
  40928. configurable: true
  40929. });
  40930. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  40931. get: function () {
  40932. return null;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  40938. // BORDER ATTRIBUTES
  40939. get: function () {
  40940. return null;
  40941. },
  40942. enumerable: true,
  40943. configurable: true
  40944. });
  40945. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  40946. get: function () {
  40947. return null;
  40948. },
  40949. enumerable: true,
  40950. configurable: true
  40951. });
  40952. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  40953. get: function () {
  40954. return null;
  40955. },
  40956. enumerable: true,
  40957. configurable: true
  40958. });
  40959. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  40960. get: function () {
  40961. return null;
  40962. },
  40963. enumerable: true,
  40964. configurable: true
  40965. });
  40966. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  40967. get: function () {
  40968. return null;
  40969. },
  40970. enumerable: true,
  40971. configurable: true
  40972. });
  40973. __decorate([
  40974. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  40975. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  40976. __decorate([
  40977. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40978. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  40979. __decorate([
  40980. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40981. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  40982. __decorate([
  40983. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  40984. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  40985. __decorate([
  40986. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  40987. ], Shape2DInstanceData.prototype, "borderThickness", null);
  40988. __decorate([
  40989. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  40990. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  40991. __decorate([
  40992. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40993. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  40994. __decorate([
  40995. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40996. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  40997. __decorate([
  40998. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  40999. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  41000. return Shape2DInstanceData;
  41001. })(BABYLON.InstanceDataBase);
  41002. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  41003. })(BABYLON || (BABYLON = {}));
  41004. var BABYLON;
  41005. (function (BABYLON) {
  41006. var Group2D = (function (_super) {
  41007. __extends(Group2D, _super);
  41008. /**
  41009. * Create an Logical or Renderable Group.
  41010. * @param settings a combination of settings, possible ones are
  41011. * - 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)
  41012. * - children: an array of direct children
  41013. * - id a text identifier, for information purpose
  41014. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41015. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41016. * - scale: the initial scale of the primitive. default is 1
  41017. * - origin: define the normalized origin point location, default [0.5;0.5]
  41018. * - 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.
  41019. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  41020. * - 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).
  41021. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  41022. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41023. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41024. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41025. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41026. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41027. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41028. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41029. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41030. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41031. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41032. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41033. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41034. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41035. */
  41036. function Group2D(settings) {
  41037. if (settings == null) {
  41038. settings = {};
  41039. }
  41040. if (settings.origin == null) {
  41041. settings.origin = new BABYLON.Vector2(0, 0);
  41042. }
  41043. _super.call(this, settings);
  41044. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  41045. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  41046. if (this._trackedNode && this.owner) {
  41047. this.owner._registerTrackedNode(this);
  41048. }
  41049. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  41050. this.size = size;
  41051. this._viewportPosition = BABYLON.Vector2.Zero();
  41052. }
  41053. Group2D._createCachedCanvasGroup = function (owner) {
  41054. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  41055. return g;
  41056. };
  41057. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  41058. this._bindCacheTarget();
  41059. if (vertexData) {
  41060. var uv = vertexData.uvs;
  41061. var nodeuv = this._renderableData._cacheNodeUVs;
  41062. for (var i = 0; i < 4; i++) {
  41063. uv[i * 2 + 0] = nodeuv[i].x;
  41064. uv[i * 2 + 1] = nodeuv[i].y;
  41065. }
  41066. }
  41067. if (material) {
  41068. material.diffuseTexture = this._renderableData._cacheTexture;
  41069. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41070. }
  41071. this._renderableData._cacheTexture.hasAlpha = true;
  41072. this._unbindCacheTarget();
  41073. };
  41074. Object.defineProperty(Group2D.prototype, "cachedRect", {
  41075. /**
  41076. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  41077. * 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.
  41078. */
  41079. get: function () {
  41080. if (!this._renderableData) {
  41081. return null;
  41082. }
  41083. return this._renderableData._cacheNode;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  41089. /**
  41090. * The UVs into the MapTexture that map the cached group
  41091. */
  41092. get: function () {
  41093. if (!this._renderableData) {
  41094. return null;
  41095. }
  41096. return this._renderableData._cacheNodeUVs;
  41097. },
  41098. enumerable: true,
  41099. configurable: true
  41100. });
  41101. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  41102. get: function () {
  41103. if (!this._renderableData) {
  41104. return null;
  41105. }
  41106. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  41107. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  41108. }
  41109. return this._renderableData._cacheNodeUVsChangedObservable;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  41115. /**
  41116. * Access the texture that maintains a cached version of the Group2D.
  41117. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  41118. */
  41119. get: function () {
  41120. if (!this._renderableData) {
  41121. return null;
  41122. }
  41123. return this._renderableData._cacheTexture;
  41124. },
  41125. enumerable: true,
  41126. configurable: true
  41127. });
  41128. /**
  41129. * Call this method to remove this Group and its children from the Canvas
  41130. */
  41131. Group2D.prototype.dispose = function () {
  41132. if (!_super.prototype.dispose.call(this)) {
  41133. return false;
  41134. }
  41135. if (this._trackedNode != null) {
  41136. this.owner._unregisterTrackedNode(this);
  41137. this._trackedNode = null;
  41138. }
  41139. if (this._renderableData) {
  41140. this._renderableData.dispose();
  41141. this._renderableData = null;
  41142. }
  41143. return true;
  41144. };
  41145. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  41146. /**
  41147. * @returns Returns true if the Group render content, false if it's a logical group only
  41148. */
  41149. get: function () {
  41150. return this._isRenderableGroup;
  41151. },
  41152. enumerable: true,
  41153. configurable: true
  41154. });
  41155. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  41156. /**
  41157. * @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
  41158. */
  41159. get: function () {
  41160. return this._isCachedGroup;
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(Group2D.prototype, "size", {
  41166. get: function () {
  41167. return this._size;
  41168. },
  41169. /**
  41170. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  41171. * 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.
  41172. */
  41173. set: function (val) {
  41174. this._size = val;
  41175. },
  41176. enumerable: true,
  41177. configurable: true
  41178. });
  41179. Object.defineProperty(Group2D.prototype, "viewportSize", {
  41180. get: function () {
  41181. return this._viewportSize;
  41182. },
  41183. enumerable: true,
  41184. configurable: true
  41185. });
  41186. Object.defineProperty(Group2D.prototype, "actualSize", {
  41187. get: function () {
  41188. // The computed size will be floor on both width and height
  41189. var actualSize;
  41190. // Return the size if set by the user
  41191. if (this._size) {
  41192. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  41193. }
  41194. else {
  41195. var m = this.boundingInfo.max();
  41196. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  41197. }
  41198. // 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)
  41199. if (!actualSize.equals(this._actualSize)) {
  41200. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  41201. this._actualSize = actualSize;
  41202. this.handleGroupChanged(Group2D.actualSizeProperty);
  41203. }
  41204. return actualSize;
  41205. },
  41206. enumerable: true,
  41207. configurable: true
  41208. });
  41209. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  41210. /**
  41211. * 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.
  41212. * 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.
  41213. */
  41214. get: function () {
  41215. return this._cacheBehavior;
  41216. },
  41217. enumerable: true,
  41218. configurable: true
  41219. });
  41220. Group2D.prototype._addPrimToDirtyList = function (prim) {
  41221. this._renderableData._primDirtyList.push(prim);
  41222. };
  41223. Group2D.prototype._renderCachedCanvas = function () {
  41224. this.updateCachedStates(true);
  41225. var context = new BABYLON.PrepareRender2DContext();
  41226. this._prepareGroupRender(context);
  41227. this._groupRender();
  41228. };
  41229. Object.defineProperty(Group2D.prototype, "trackedNode", {
  41230. /**
  41231. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  41232. */
  41233. get: function () {
  41234. return this._trackedNode;
  41235. },
  41236. set: function (val) {
  41237. if (val != null) {
  41238. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41239. this.owner._registerTrackedNode(this);
  41240. }
  41241. this._trackedNode = val;
  41242. }
  41243. else {
  41244. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41245. this.owner._unregisterTrackedNode(this);
  41246. }
  41247. this._trackedNode = null;
  41248. }
  41249. },
  41250. enumerable: true,
  41251. configurable: true
  41252. });
  41253. Group2D.prototype.levelIntersect = function (intersectInfo) {
  41254. // 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
  41255. return true;
  41256. };
  41257. Group2D.prototype.updateLevelBoundingInfo = function () {
  41258. var size;
  41259. // If the size is set by the user, the boundingInfo is computed from this value
  41260. if (this.size) {
  41261. size = this.size;
  41262. }
  41263. else {
  41264. size = new BABYLON.Size(0, 0);
  41265. }
  41266. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  41267. };
  41268. // Method called only on renderable groups to prepare the rendering
  41269. Group2D.prototype._prepareGroupRender = function (context) {
  41270. var sortedDirtyList = null;
  41271. // Update the Global Transformation and visibility status of the changed primitives
  41272. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  41273. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  41274. this.updateCachedStatesOf(sortedDirtyList, true);
  41275. }
  41276. // Setup the size of the rendering viewport
  41277. // 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
  41278. if (!this._isCachedGroup) {
  41279. // Compute the WebGL viewport's location/size
  41280. var t = this._globalTransform.getTranslation();
  41281. var s = this.actualSize.clone();
  41282. var rs = this.owner._renderingSize;
  41283. s.height = Math.min(s.height, rs.height - t.y);
  41284. s.width = Math.min(s.width, rs.width - t.x);
  41285. var x = t.x;
  41286. var y = t.y;
  41287. // 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
  41288. this._viewportPosition.x = x;
  41289. this._viewportPosition.y = y;
  41290. var vw = s.width;
  41291. var vh = s.height;
  41292. if (!this._viewportSize) {
  41293. this._viewportSize = new BABYLON.Size(vw, vh);
  41294. }
  41295. else {
  41296. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  41297. context.forceRefreshPrimitive = true;
  41298. }
  41299. this._viewportSize.width = vw;
  41300. this._viewportSize.height = vh;
  41301. }
  41302. }
  41303. else {
  41304. var newSize = this.actualSize.clone();
  41305. if (!newSize.equals(this._viewportSize)) {
  41306. context.forceRefreshPrimitive = true;
  41307. }
  41308. this._viewportSize = newSize;
  41309. }
  41310. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  41311. // If the group is cached, set the dirty flag to true because of the incoming changes
  41312. this._cacheGroupDirty = this._isCachedGroup;
  41313. // If it's a force refresh, prepare all the children
  41314. if (context.forceRefreshPrimitive) {
  41315. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41316. var p = _a[_i];
  41317. p._prepareRender(context);
  41318. }
  41319. }
  41320. else {
  41321. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  41322. // the hierarchyDepth in order to prepare primitives from top to bottom
  41323. if (!sortedDirtyList) {
  41324. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  41325. }
  41326. sortedDirtyList.forEach(function (p) {
  41327. // 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.
  41328. // 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.
  41329. if (!p.isDisposed && p._needPrepare()) {
  41330. p._prepareRender(context);
  41331. }
  41332. });
  41333. // Everything is updated, clear the dirty list
  41334. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  41335. this._renderableData._primDirtyList.splice(0);
  41336. }
  41337. }
  41338. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  41339. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  41340. g._prepareGroupRender(context);
  41341. });
  41342. };
  41343. Group2D.prototype._groupRender = function () {
  41344. var _this = this;
  41345. var engine = this.owner.engine;
  41346. var failedCount = 0;
  41347. // First recurse to children render group to render them (in their cache or on screen)
  41348. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  41349. var childGroup = _a[_i];
  41350. childGroup._groupRender();
  41351. }
  41352. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  41353. if (!this.isCachedGroup || this._cacheGroupDirty) {
  41354. if (this.isCachedGroup) {
  41355. this._bindCacheTarget();
  41356. }
  41357. else {
  41358. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  41359. }
  41360. var curAlphaTest = engine.getAlphaTesting() === true;
  41361. var curDepthWrite = engine.getDepthWrite() === true;
  41362. // ===================================================================
  41363. // First pass, update the InstancedArray and render Opaque primitives
  41364. // Disable Alpha Testing, Enable Depth Write
  41365. engine.setAlphaTesting(false);
  41366. engine.setDepthWrite(true);
  41367. // For each different model of primitive to render
  41368. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  41369. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  41370. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  41371. var renderCount = _this._prepareContext(engine, context, v);
  41372. // If null is returned, there's no opaque data to render
  41373. if (renderCount === null) {
  41374. return;
  41375. }
  41376. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  41377. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  41378. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  41379. var renderFailed = !v.modelRenderCache.render(v, context);
  41380. // Update dirty flag/related
  41381. v.opaqueDirty = renderFailed;
  41382. failedCount += renderFailed ? 1 : 0;
  41383. }
  41384. });
  41385. // =======================================================================
  41386. // Second pass, update the InstancedArray and render AlphaTest primitives
  41387. // Enable Alpha Testing, Enable Depth Write
  41388. engine.setAlphaTesting(true);
  41389. engine.setDepthWrite(true);
  41390. // For each different model of primitive to render
  41391. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  41392. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  41393. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  41394. var renderCount = _this._prepareContext(engine, context, v);
  41395. // If null is returned, there's no opaque data to render
  41396. if (renderCount === null) {
  41397. return;
  41398. }
  41399. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  41400. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  41401. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  41402. var renderFailed = !v.modelRenderCache.render(v, context);
  41403. // Update dirty flag/related
  41404. v.opaqueDirty = renderFailed;
  41405. failedCount += renderFailed ? 1 : 0;
  41406. }
  41407. });
  41408. // =======================================================================
  41409. // Third pass, transparent primitive rendering
  41410. // Enable Alpha Testing, Disable Depth Write
  41411. engine.setAlphaTesting(true);
  41412. engine.setDepthWrite(false);
  41413. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  41414. if (this._renderableData._transparentListChanged) {
  41415. this._updateTransparentData();
  41416. }
  41417. // From this point on we have up to date data to render, so let's go
  41418. failedCount += this._renderTransparentData();
  41419. // =======================================================================
  41420. // Unbind target/restore viewport setting, clear dirty flag, and quit
  41421. // The group's content is no longer dirty
  41422. this._cacheGroupDirty = failedCount !== 0;
  41423. if (this.isCachedGroup) {
  41424. this._unbindCacheTarget();
  41425. }
  41426. else {
  41427. if (curVP) {
  41428. engine.setViewport(curVP);
  41429. }
  41430. }
  41431. // Restore saved states
  41432. engine.setAlphaTesting(curAlphaTest);
  41433. engine.setDepthWrite(curDepthWrite);
  41434. }
  41435. };
  41436. Group2D.prototype._updateTransparentData = function () {
  41437. var rd = this._renderableData;
  41438. // If null, there was no change of ZOrder, we have nothing to do
  41439. if (rd._firstChangedPrim === null) {
  41440. return;
  41441. }
  41442. // Sort all the primitive from their depth, max (bottom) to min (top)
  41443. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  41444. var checkAndAddPrimInSegment = function (seg, tpiI) {
  41445. var tpi = rd._transparentPrimitives[tpiI];
  41446. // Fast rejection: if gii are different
  41447. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  41448. return false;
  41449. }
  41450. var tpiZ = tpi._primitive.actualZOffset;
  41451. // We've made it so far, the tpi can be part of the segment, add it
  41452. tpi._transparentSegment = seg;
  41453. // Check if we have to update endZ, a smaller value means one above the current one
  41454. if (tpiZ < seg.endZ) {
  41455. seg.endZ = tpiZ;
  41456. seg.endDataIndex = tpi._primitive._getLastIndexInDataBuffer() + 1; // Still exclusive
  41457. }
  41458. return true;
  41459. };
  41460. rd._transparentSegments.splice(0);
  41461. var prevSeg = null;
  41462. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  41463. var tpi = rd._transparentPrimitives[tpiI];
  41464. // Check if the Data in which the primitive is stored is not sorted properly
  41465. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  41466. tpi._groupInstanceInfo.sortTransparentData();
  41467. }
  41468. // Reset the segment, we have to create/rebuild it
  41469. tpi._transparentSegment = null;
  41470. // If there's a previous valid segment, check if this prim can be part of it
  41471. if (prevSeg) {
  41472. checkAndAddPrimInSegment(prevSeg, tpiI);
  41473. }
  41474. // If we couldn't insert in the adjacent segments, he have to create one
  41475. if (!tpi._transparentSegment) {
  41476. var ts = new BABYLON.TransparentSegment();
  41477. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  41478. var prim = tpi._primitive;
  41479. ts.startZ = prim.actualZOffset;
  41480. ts.startDataIndex = prim._getFirstIndexInDataBuffer();
  41481. ts.endDataIndex = prim._getLastIndexInDataBuffer() + 1; // Make it exclusive, more natural to use in a for loop
  41482. ts.endZ = ts.startZ;
  41483. tpi._transparentSegment = ts;
  41484. rd._transparentSegments.push(ts);
  41485. }
  41486. // Update prevSeg
  41487. prevSeg = tpi._transparentSegment;
  41488. }
  41489. rd._firstChangedPrim = null;
  41490. rd._transparentListChanged = false;
  41491. };
  41492. Group2D.prototype._renderTransparentData = function () {
  41493. var failedCount = 0;
  41494. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  41495. var rd = this._renderableData;
  41496. var length = rd._transparentSegments.length;
  41497. for (var i = 0; i < length; i++) {
  41498. var ts = rd._transparentSegments[i];
  41499. var gii = ts.groupInsanceInfo;
  41500. var mrc = gii.modelRenderCache;
  41501. context.useInstancing = false;
  41502. context.partDataStartIndex = ts.startDataIndex;
  41503. context.partDataEndIndex = ts.endDataIndex;
  41504. context.groupInfoPartData = gii.transparentData;
  41505. var renderFailed = !mrc.render(gii, context);
  41506. failedCount += renderFailed ? 1 : 0;
  41507. }
  41508. return failedCount;
  41509. };
  41510. Group2D.prototype._prepareContext = function (engine, context, gii) {
  41511. var gipd = null;
  41512. var setDirty;
  41513. var getDirty;
  41514. // Render Mode specifics
  41515. switch (context.renderMode) {
  41516. case BABYLON.Render2DContext.RenderModeOpaque:
  41517. {
  41518. if (!gii.hasOpaqueData) {
  41519. return null;
  41520. }
  41521. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  41522. getDirty = function () { return gii.opaqueDirty; };
  41523. context.groupInfoPartData = gii.opaqueData;
  41524. gipd = gii.opaqueData;
  41525. break;
  41526. }
  41527. case BABYLON.Render2DContext.RenderModeAlphaTest:
  41528. {
  41529. if (!gii.hasAlphaTestData) {
  41530. return null;
  41531. }
  41532. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  41533. getDirty = function () { return gii.alphaTestDirty; };
  41534. context.groupInfoPartData = gii.alphaTestData;
  41535. gipd = gii.alphaTestData;
  41536. break;
  41537. }
  41538. default:
  41539. throw new Error("_prepareContext is only for opaque or alphaTest");
  41540. }
  41541. var renderCount = 0;
  41542. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  41543. // Skip it if instanced arrays are not supported
  41544. if (this.owner.supportInstancedArray) {
  41545. // Flag for instancing
  41546. context.useInstancing = true;
  41547. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  41548. for (var i = 0; i < gipd.length; i++) {
  41549. var pid = gipd[i];
  41550. // If the instances of the model was changed, pack the data
  41551. var array = pid._partData;
  41552. var instanceData_1 = array.pack();
  41553. renderCount += array.usedElementCount;
  41554. // Compute the size the instance buffer should have
  41555. var neededSize = array.usedElementCount * array.stride * 4;
  41556. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  41557. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  41558. if (pid._partBuffer) {
  41559. engine.deleteInstancesBuffer(pid._partBuffer);
  41560. }
  41561. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  41562. pid._partBufferSize = neededSize;
  41563. setDirty(false);
  41564. // Update the WebGL buffer to match the new content of the instances data
  41565. engine.updateArrayBuffer(instanceData_1);
  41566. }
  41567. else if (getDirty()) {
  41568. // Update the WebGL buffer to match the new content of the instances data
  41569. engine.bindArrayBuffer(pid._partBuffer);
  41570. engine.updateArrayBuffer(instanceData_1);
  41571. }
  41572. }
  41573. setDirty(false);
  41574. }
  41575. else {
  41576. context.partDataStartIndex = 0;
  41577. // Find the first valid object to get the count
  41578. if (context.groupInfoPartData.length > 0) {
  41579. var i = 0;
  41580. while (!context.groupInfoPartData[i]) {
  41581. i++;
  41582. }
  41583. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  41584. }
  41585. }
  41586. return renderCount;
  41587. };
  41588. Group2D.prototype._setRenderingScale = function (scale) {
  41589. if (this._renderableData._renderingScale === scale) {
  41590. return;
  41591. }
  41592. this._renderableData._renderingScale = scale;
  41593. };
  41594. Group2D.prototype._bindCacheTarget = function () {
  41595. var curWidth;
  41596. var curHeight;
  41597. var rd = this._renderableData;
  41598. var rs = rd._renderingScale;
  41599. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  41600. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  41601. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  41602. if (rd._cacheNode) {
  41603. var size = rd._cacheNode.contentSize;
  41604. // Check if we have to deallocate because the size is too small
  41605. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  41606. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  41607. // For World space: no over-provisioning
  41608. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  41609. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  41610. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  41611. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  41612. rd._cacheTexture.freeRect(rd._cacheNode);
  41613. rd._cacheNode = null;
  41614. }
  41615. }
  41616. if (!rd._cacheNode) {
  41617. // Check if we have to allocate a rendering zone in the global cache texture
  41618. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  41619. rd._cacheNode = res.node;
  41620. rd._cacheTexture = res.texture;
  41621. rd._cacheRenderSprite = res.sprite;
  41622. sizeChanged = true;
  41623. }
  41624. if (sizeChanged) {
  41625. rd._cacheSize.copyFrom(Group2D._s);
  41626. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  41627. this.scale = this._renderableData._renderingScale;
  41628. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  41629. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  41630. }
  41631. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  41632. }
  41633. var n = rd._cacheNode;
  41634. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  41635. };
  41636. Group2D.prototype._unbindCacheTarget = function () {
  41637. if (this._renderableData._cacheTexture) {
  41638. this._renderableData._cacheTexture.unbindTexture();
  41639. }
  41640. };
  41641. Group2D.prototype.handleGroupChanged = function (prop) {
  41642. // This method is only for cachedGroup
  41643. var rd = this._renderableData;
  41644. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  41645. return;
  41646. }
  41647. // For now we only support these property changes
  41648. // TODO: add more! :)
  41649. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  41650. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  41651. }
  41652. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  41653. rd._cacheRenderSprite.rotation = this.rotation;
  41654. }
  41655. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  41656. rd._cacheRenderSprite.scale = this.scale;
  41657. }
  41658. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  41659. rd._cacheRenderSprite.origin = this.origin.clone();
  41660. }
  41661. else if (prop.id === Group2D.actualSizeProperty.id) {
  41662. rd._cacheRenderSprite.size = this.actualSize.clone();
  41663. }
  41664. };
  41665. Group2D.prototype.detectGroupStates = function () {
  41666. var isCanvas = this instanceof BABYLON.Canvas2D;
  41667. var canvasStrat = this.owner.cachingStrategy;
  41668. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  41669. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  41670. this._isRenderableGroup = isCanvas;
  41671. this._isCachedGroup = false;
  41672. }
  41673. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  41674. if (isCanvas) {
  41675. this._isRenderableGroup = true;
  41676. this._isCachedGroup = true;
  41677. }
  41678. else {
  41679. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  41680. this._isCachedGroup = false;
  41681. }
  41682. }
  41683. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  41684. if (isCanvas) {
  41685. this._isRenderableGroup = true;
  41686. this._isCachedGroup = false;
  41687. }
  41688. else {
  41689. if (this.hierarchyDepth === 1) {
  41690. this._isRenderableGroup = true;
  41691. this._isCachedGroup = true;
  41692. }
  41693. else {
  41694. this._isRenderableGroup = false;
  41695. this._isCachedGroup = false;
  41696. }
  41697. }
  41698. }
  41699. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  41700. var gcb = this.cacheBehavior;
  41701. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  41702. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  41703. this._isCachedGroup = false;
  41704. }
  41705. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  41706. this._isRenderableGroup = true;
  41707. this._isCachedGroup = true;
  41708. }
  41709. }
  41710. if (this._isRenderableGroup) {
  41711. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  41712. if (!this._renderableData) {
  41713. this._renderableData = new RenderableGroupData();
  41714. }
  41715. }
  41716. // If the group is tagged as renderable we add it to the renderable tree
  41717. if (this._isCachedGroup) {
  41718. var cur = this.parent;
  41719. while (cur) {
  41720. if (cur instanceof Group2D && cur._isRenderableGroup) {
  41721. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  41722. cur._renderableData._childrenRenderableGroups.push(this);
  41723. }
  41724. break;
  41725. }
  41726. cur = cur.parent;
  41727. }
  41728. }
  41729. };
  41730. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41731. /**
  41732. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  41733. */
  41734. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  41735. /**
  41736. * When used, this group's content won't be cached, no matter which strategy used.
  41737. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  41738. */
  41739. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  41740. /**
  41741. * When used, the group's content will be cached in the nearest cached parent group/canvas
  41742. */
  41743. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  41744. Group2D._s = BABYLON.Size.Zero();
  41745. __decorate([
  41746. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  41747. ], Group2D.prototype, "size", null);
  41748. __decorate([
  41749. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  41750. ], Group2D.prototype, "actualSize", null);
  41751. Group2D = __decorate([
  41752. BABYLON.className("Group2D")
  41753. ], Group2D);
  41754. return Group2D;
  41755. })(BABYLON.Prim2DBase);
  41756. BABYLON.Group2D = Group2D;
  41757. var RenderableGroupData = (function () {
  41758. function RenderableGroupData() {
  41759. this._primDirtyList = new Array();
  41760. this._childrenRenderableGroups = new Array();
  41761. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  41762. this._transparentPrimitives = new Array();
  41763. this._transparentSegments = new Array();
  41764. this._firstChangedPrim = null;
  41765. this._transparentListChanged = false;
  41766. this._cacheNode = null;
  41767. this._cacheTexture = null;
  41768. this._cacheRenderSprite = null;
  41769. this._renderingScale = 1;
  41770. this._cacheNodeUVs = null;
  41771. this._cacheNodeUVsChangedObservable = null;
  41772. this._cacheSize = BABYLON.Size.Zero();
  41773. this._useMipMap = false;
  41774. this._anisotropicLevel = 1;
  41775. }
  41776. RenderableGroupData.prototype.dispose = function () {
  41777. if (this._cacheRenderSprite) {
  41778. this._cacheRenderSprite.dispose();
  41779. this._cacheRenderSprite = null;
  41780. }
  41781. if (this._cacheTexture && this._cacheNode) {
  41782. this._cacheTexture.freeRect(this._cacheNode);
  41783. this._cacheTexture = null;
  41784. this._cacheNode = null;
  41785. }
  41786. if (this._primDirtyList) {
  41787. this._primDirtyList.splice(0);
  41788. this._primDirtyList = null;
  41789. }
  41790. if (this._renderGroupInstancesInfo) {
  41791. this._renderGroupInstancesInfo.forEach(function (k, v) {
  41792. v.dispose();
  41793. });
  41794. this._renderGroupInstancesInfo = null;
  41795. }
  41796. if (this._cacheNodeUVsChangedObservable) {
  41797. this._cacheNodeUVsChangedObservable.clear();
  41798. this._cacheNodeUVsChangedObservable = null;
  41799. }
  41800. };
  41801. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  41802. var tpi = new TransparentPrimitiveInfo();
  41803. tpi._primitive = prim;
  41804. tpi._groupInstanceInfo = gii;
  41805. tpi._transparentSegment = null;
  41806. this._transparentPrimitives.push(tpi);
  41807. this._transparentListChanged = true;
  41808. this.updateSmallestZChangedPrim(tpi);
  41809. return tpi;
  41810. };
  41811. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  41812. var index = this._transparentPrimitives.indexOf(tpi);
  41813. if (index !== -1) {
  41814. this._transparentPrimitives.splice(index, 1);
  41815. this._transparentListChanged = true;
  41816. this.updateSmallestZChangedPrim(tpi);
  41817. }
  41818. };
  41819. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  41820. this._transparentListChanged = true;
  41821. this.updateSmallestZChangedPrim(tpi);
  41822. };
  41823. RenderableGroupData.prototype.updateSmallestZChangedPrim = function (tpi) {
  41824. if (tpi._primitive) {
  41825. var newZ = tpi._primitive.actualZOffset;
  41826. var curZ = this._firstChangedPrim ? this._firstChangedPrim._primitive.actualZOffset : Number.MIN_VALUE;
  41827. if (newZ > curZ) {
  41828. this._firstChangedPrim = tpi;
  41829. }
  41830. }
  41831. };
  41832. return RenderableGroupData;
  41833. })();
  41834. BABYLON.RenderableGroupData = RenderableGroupData;
  41835. var TransparentPrimitiveInfo = (function () {
  41836. function TransparentPrimitiveInfo() {
  41837. }
  41838. return TransparentPrimitiveInfo;
  41839. })();
  41840. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  41841. })(BABYLON || (BABYLON = {}));
  41842. var BABYLON;
  41843. (function (BABYLON) {
  41844. var Rectangle2DRenderCache = (function (_super) {
  41845. __extends(Rectangle2DRenderCache, _super);
  41846. function Rectangle2DRenderCache(engine, modelKey) {
  41847. _super.call(this, engine, modelKey);
  41848. this.effectsReady = false;
  41849. this.fillVB = null;
  41850. this.fillIB = null;
  41851. this.fillIndicesCount = 0;
  41852. this.instancingFillAttributes = null;
  41853. this.effectFill = null;
  41854. this.effectFillInstanced = null;
  41855. this.borderVB = null;
  41856. this.borderIB = null;
  41857. this.borderIndicesCount = 0;
  41858. this.instancingBorderAttributes = null;
  41859. this.effectBorder = null;
  41860. this.effectBorderInstanced = null;
  41861. }
  41862. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  41863. // Do nothing if the shader is still loading/preparing
  41864. if (!this.effectsReady) {
  41865. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  41866. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  41867. return false;
  41868. }
  41869. this.effectsReady = true;
  41870. }
  41871. var engine = instanceInfo.owner.owner.engine;
  41872. var depthFunction = 0;
  41873. if (this.effectFill && this.effectBorder) {
  41874. depthFunction = engine.getDepthFunction();
  41875. engine.setDepthFunctionToLessOrEqual();
  41876. }
  41877. var curAlphaMode = engine.getAlphaMode();
  41878. if (this.effectFill) {
  41879. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  41880. var pid = context.groupInfoPartData[partIndex];
  41881. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41882. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41883. }
  41884. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  41885. engine.enableEffect(effect);
  41886. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  41887. if (context.useInstancing) {
  41888. if (!this.instancingFillAttributes) {
  41889. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  41890. }
  41891. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  41892. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  41893. engine.unbindInstanceAttributes();
  41894. }
  41895. else {
  41896. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41897. this.setupUniforms(effect, partIndex, pid._partData, i);
  41898. engine.draw(true, 0, this.fillIndicesCount);
  41899. }
  41900. }
  41901. }
  41902. if (this.effectBorder) {
  41903. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  41904. var pid = context.groupInfoPartData[partIndex];
  41905. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41906. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41907. }
  41908. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  41909. engine.enableEffect(effect);
  41910. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  41911. if (context.useInstancing) {
  41912. if (!this.instancingBorderAttributes) {
  41913. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  41914. }
  41915. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  41916. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  41917. engine.unbindInstanceAttributes();
  41918. }
  41919. else {
  41920. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41921. this.setupUniforms(effect, partIndex, pid._partData, i);
  41922. engine.draw(true, 0, this.borderIndicesCount);
  41923. }
  41924. }
  41925. }
  41926. engine.setAlphaMode(curAlphaMode);
  41927. if (this.effectFill && this.effectBorder) {
  41928. engine.setDepthFunction(depthFunction);
  41929. }
  41930. return true;
  41931. };
  41932. Rectangle2DRenderCache.prototype.dispose = function () {
  41933. if (!_super.prototype.dispose.call(this)) {
  41934. return false;
  41935. }
  41936. if (this.fillVB) {
  41937. this._engine._releaseBuffer(this.fillVB);
  41938. this.fillVB = null;
  41939. }
  41940. if (this.fillIB) {
  41941. this._engine._releaseBuffer(this.fillIB);
  41942. this.fillIB = null;
  41943. }
  41944. if (this.effectFill) {
  41945. this._engine._releaseEffect(this.effectFill);
  41946. this.effectFill = null;
  41947. }
  41948. if (this.effectFillInstanced) {
  41949. this._engine._releaseEffect(this.effectFillInstanced);
  41950. this.effectFillInstanced = null;
  41951. }
  41952. if (this.borderVB) {
  41953. this._engine._releaseBuffer(this.borderVB);
  41954. this.borderVB = null;
  41955. }
  41956. if (this.borderIB) {
  41957. this._engine._releaseBuffer(this.borderIB);
  41958. this.borderIB = null;
  41959. }
  41960. if (this.effectBorder) {
  41961. this._engine._releaseEffect(this.effectBorder);
  41962. this.effectBorder = null;
  41963. }
  41964. if (this.effectBorderInstanced) {
  41965. this._engine._releaseEffect(this.effectBorderInstanced);
  41966. this.effectBorderInstanced = null;
  41967. }
  41968. return true;
  41969. };
  41970. return Rectangle2DRenderCache;
  41971. })(BABYLON.ModelRenderCache);
  41972. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  41973. var Rectangle2DInstanceData = (function (_super) {
  41974. __extends(Rectangle2DInstanceData, _super);
  41975. function Rectangle2DInstanceData(partId) {
  41976. _super.call(this, partId, 1);
  41977. }
  41978. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  41979. get: function () {
  41980. return null;
  41981. },
  41982. enumerable: true,
  41983. configurable: true
  41984. });
  41985. __decorate([
  41986. BABYLON.instanceData()
  41987. ], Rectangle2DInstanceData.prototype, "properties", null);
  41988. return Rectangle2DInstanceData;
  41989. })(BABYLON.Shape2DInstanceData);
  41990. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  41991. var Rectangle2D = (function (_super) {
  41992. __extends(Rectangle2D, _super);
  41993. /**
  41994. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  41995. * @param settings a combination of settings, possible ones are
  41996. * - 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)
  41997. * - children: an array of direct children
  41998. * - id a text identifier, for information purpose
  41999. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  42000. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42001. * - scale: the initial scale of the primitive. default is 1
  42002. * - origin: define the normalized origin point location, default [0.5;0.5]
  42003. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  42004. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  42005. * - 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)
  42006. * - 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)
  42007. * - borderThickness: the thickness of the drawn border, default is 1.
  42008. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42009. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42010. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42011. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42012. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42013. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42014. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42015. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42016. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42017. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42018. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42019. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42020. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42021. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42022. */
  42023. function Rectangle2D(settings) {
  42024. // Avoid checking every time if the object exists
  42025. if (settings == null) {
  42026. settings = {};
  42027. }
  42028. _super.call(this, settings);
  42029. if (settings.size != null) {
  42030. this.size = settings.size;
  42031. }
  42032. else if (settings.width || settings.height) {
  42033. var size = new BABYLON.Size(settings.width, settings.height);
  42034. this.size = size;
  42035. }
  42036. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  42037. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  42038. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  42039. //this.size = size;
  42040. this.roundRadius = roundRadius;
  42041. this.borderThickness = borderThickness;
  42042. }
  42043. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  42044. get: function () {
  42045. if (this._actualSize) {
  42046. return this._actualSize;
  42047. }
  42048. return this.size;
  42049. },
  42050. set: function (value) {
  42051. this._actualSize = value;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  42057. get: function () {
  42058. return this._notRounded;
  42059. },
  42060. set: function (value) {
  42061. this._notRounded = value;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  42067. get: function () {
  42068. return this._roundRadius;
  42069. },
  42070. set: function (value) {
  42071. this._roundRadius = value;
  42072. this.notRounded = value === 0;
  42073. this._positioningDirty();
  42074. },
  42075. enumerable: true,
  42076. configurable: true
  42077. });
  42078. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  42079. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  42080. if (this.notRounded) {
  42081. return true;
  42082. }
  42083. // 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.
  42084. // 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)
  42085. // 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.
  42086. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  42087. var size = this.size;
  42088. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  42089. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  42090. var rr = this.roundRadius;
  42091. var rrs = rr * rr;
  42092. // Check if the point is in the bottom/left quarter area
  42093. Rectangle2D._i1.x = rr;
  42094. Rectangle2D._i1.y = rr;
  42095. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42096. // Compute the intersection point in the quarter local space
  42097. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42098. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42099. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42100. return Rectangle2D._i2.lengthSquared() <= rrs;
  42101. }
  42102. // Check if the point is in the top/left quarter area
  42103. Rectangle2D._i1.x = rr;
  42104. Rectangle2D._i1.y = size.height - rr;
  42105. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42106. // Compute the intersection point in the quarter local space
  42107. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42108. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42109. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42110. return Rectangle2D._i2.lengthSquared() <= rrs;
  42111. }
  42112. // Check if the point is in the top/right quarter area
  42113. Rectangle2D._i1.x = size.width - rr;
  42114. Rectangle2D._i1.y = size.height - rr;
  42115. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42116. // Compute the intersection point in the quarter local space
  42117. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42118. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42119. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42120. return Rectangle2D._i2.lengthSquared() <= rrs;
  42121. }
  42122. // Check if the point is in the bottom/right quarter area
  42123. Rectangle2D._i1.x = size.width - rr;
  42124. Rectangle2D._i1.y = rr;
  42125. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42126. // Compute the intersection point in the quarter local space
  42127. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42128. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42129. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42130. return Rectangle2D._i2.lengthSquared() <= rrs;
  42131. }
  42132. // At any other locations the point is guarantied to be inside
  42133. return true;
  42134. };
  42135. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  42136. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42137. };
  42138. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  42139. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  42140. return renderCache;
  42141. };
  42142. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42143. var renderCache = modelRenderCache;
  42144. var engine = this.owner.engine;
  42145. // Need to create WebGL resources for fill part?
  42146. if (this.fill) {
  42147. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  42148. var vb = new Float32Array(vbSize);
  42149. for (var i = 0; i < vbSize; i++) {
  42150. vb[i] = i;
  42151. }
  42152. renderCache.fillVB = engine.createVertexBuffer(vb);
  42153. var triCount = vbSize - 1;
  42154. var ib = new Float32Array(triCount * 3);
  42155. for (var i = 0; i < triCount; i++) {
  42156. ib[i * 3 + 0] = 0;
  42157. ib[i * 3 + 2] = i + 1;
  42158. ib[i * 3 + 1] = i + 2;
  42159. }
  42160. ib[triCount * 3 - 2] = 1;
  42161. renderCache.fillIB = engine.createIndexBuffer(ib);
  42162. renderCache.fillIndicesCount = triCount * 3;
  42163. // 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
  42164. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  42165. if (ei) {
  42166. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42167. }
  42168. // Get the non instanced version
  42169. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  42170. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42171. }
  42172. // Need to create WebGL resource for border part?
  42173. if (this.border) {
  42174. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  42175. var vb = new Float32Array(vbSize);
  42176. for (var i = 0; i < vbSize; i++) {
  42177. vb[i] = i;
  42178. }
  42179. renderCache.borderVB = engine.createVertexBuffer(vb);
  42180. var triCount = vbSize;
  42181. var rs = triCount / 2;
  42182. var ib = new Float32Array(triCount * 3);
  42183. for (var i = 0; i < rs; i++) {
  42184. var r0 = i;
  42185. var r1 = (i + 1) % rs;
  42186. ib[i * 6 + 0] = rs + r1;
  42187. ib[i * 6 + 1] = rs + r0;
  42188. ib[i * 6 + 2] = r0;
  42189. ib[i * 6 + 3] = r1;
  42190. ib[i * 6 + 4] = rs + r1;
  42191. ib[i * 6 + 5] = r0;
  42192. }
  42193. renderCache.borderIB = engine.createIndexBuffer(ib);
  42194. renderCache.borderIndicesCount = triCount * 3;
  42195. // 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
  42196. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  42197. if (ei) {
  42198. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42199. }
  42200. // Get the non instanced version
  42201. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  42202. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42203. }
  42204. return renderCache;
  42205. };
  42206. // 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
  42207. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42208. // Fall back to default implementation if there's no round Radius
  42209. if (this._notRounded) {
  42210. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  42211. }
  42212. else {
  42213. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  42214. initialContentPosition.x = initialContentPosition.y = rr;
  42215. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  42216. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  42217. }
  42218. };
  42219. Rectangle2D.prototype.createInstanceDataParts = function () {
  42220. var res = new Array();
  42221. if (this.border) {
  42222. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42223. }
  42224. if (this.fill) {
  42225. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42226. }
  42227. return res;
  42228. };
  42229. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  42230. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42231. return false;
  42232. }
  42233. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42234. var d = part;
  42235. var size = this.actualSize;
  42236. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  42237. }
  42238. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  42239. var d = part;
  42240. var size = this.actualSize;
  42241. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  42242. }
  42243. return true;
  42244. };
  42245. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  42246. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  42247. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  42248. Rectangle2D.roundSubdivisions = 16;
  42249. __decorate([
  42250. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  42251. ], Rectangle2D.prototype, "actualSize", null);
  42252. __decorate([
  42253. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  42254. ], Rectangle2D.prototype, "notRounded", null);
  42255. __decorate([
  42256. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  42257. ], Rectangle2D.prototype, "roundRadius", null);
  42258. Rectangle2D = __decorate([
  42259. BABYLON.className("Rectangle2D")
  42260. ], Rectangle2D);
  42261. return Rectangle2D;
  42262. })(BABYLON.Shape2D);
  42263. BABYLON.Rectangle2D = Rectangle2D;
  42264. })(BABYLON || (BABYLON = {}));
  42265. var BABYLON;
  42266. (function (BABYLON) {
  42267. var Ellipse2DRenderCache = (function (_super) {
  42268. __extends(Ellipse2DRenderCache, _super);
  42269. function Ellipse2DRenderCache(engine, modelKey) {
  42270. _super.call(this, engine, modelKey);
  42271. this.effectsReady = false;
  42272. this.fillVB = null;
  42273. this.fillIB = null;
  42274. this.fillIndicesCount = 0;
  42275. this.instancingFillAttributes = null;
  42276. this.effectFillInstanced = null;
  42277. this.effectFill = null;
  42278. this.borderVB = null;
  42279. this.borderIB = null;
  42280. this.borderIndicesCount = 0;
  42281. this.instancingBorderAttributes = null;
  42282. this.effectBorderInstanced = null;
  42283. this.effectBorder = null;
  42284. }
  42285. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  42286. // Do nothing if the shader is still loading/preparing
  42287. if (!this.effectsReady) {
  42288. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42289. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42290. return false;
  42291. }
  42292. this.effectsReady = true;
  42293. }
  42294. var engine = instanceInfo.owner.owner.engine;
  42295. var depthFunction = 0;
  42296. if (this.effectFill && this.effectBorder) {
  42297. depthFunction = engine.getDepthFunction();
  42298. engine.setDepthFunctionToLessOrEqual();
  42299. }
  42300. var curAlphaMode = engine.getAlphaMode();
  42301. if (this.effectFill) {
  42302. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42303. var pid = context.groupInfoPartData[partIndex];
  42304. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42305. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42306. }
  42307. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42308. engine.enableEffect(effect);
  42309. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42310. if (context.useInstancing) {
  42311. if (!this.instancingFillAttributes) {
  42312. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42313. }
  42314. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  42315. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  42316. engine.unbindInstanceAttributes();
  42317. }
  42318. else {
  42319. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42320. this.setupUniforms(effect, partIndex, pid._partData, i);
  42321. engine.draw(true, 0, this.fillIndicesCount);
  42322. }
  42323. }
  42324. }
  42325. if (this.effectBorder) {
  42326. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42327. var pid = context.groupInfoPartData[partIndex];
  42328. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42329. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42330. }
  42331. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42332. engine.enableEffect(effect);
  42333. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42334. if (context.useInstancing) {
  42335. if (!this.instancingBorderAttributes) {
  42336. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42337. }
  42338. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  42339. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  42340. engine.unbindInstanceAttributes();
  42341. }
  42342. else {
  42343. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42344. this.setupUniforms(effect, partIndex, pid._partData, i);
  42345. engine.draw(true, 0, this.borderIndicesCount);
  42346. }
  42347. }
  42348. }
  42349. engine.setAlphaMode(curAlphaMode);
  42350. if (this.effectFill && this.effectBorder) {
  42351. engine.setDepthFunction(depthFunction);
  42352. }
  42353. return true;
  42354. };
  42355. Ellipse2DRenderCache.prototype.dispose = function () {
  42356. if (!_super.prototype.dispose.call(this)) {
  42357. return false;
  42358. }
  42359. if (this.fillVB) {
  42360. this._engine._releaseBuffer(this.fillVB);
  42361. this.fillVB = null;
  42362. }
  42363. if (this.fillIB) {
  42364. this._engine._releaseBuffer(this.fillIB);
  42365. this.fillIB = null;
  42366. }
  42367. if (this.effectFill) {
  42368. this._engine._releaseEffect(this.effectFill);
  42369. this.effectFill = null;
  42370. }
  42371. if (this.effectFillInstanced) {
  42372. this._engine._releaseEffect(this.effectFillInstanced);
  42373. this.effectFillInstanced = null;
  42374. }
  42375. if (this.borderVB) {
  42376. this._engine._releaseBuffer(this.borderVB);
  42377. this.borderVB = null;
  42378. }
  42379. if (this.borderIB) {
  42380. this._engine._releaseBuffer(this.borderIB);
  42381. this.borderIB = null;
  42382. }
  42383. if (this.effectBorder) {
  42384. this._engine._releaseEffect(this.effectBorder);
  42385. this.effectBorder = null;
  42386. }
  42387. if (this.effectBorderInstanced) {
  42388. this._engine._releaseEffect(this.effectBorderInstanced);
  42389. this.effectBorderInstanced = null;
  42390. }
  42391. return true;
  42392. };
  42393. return Ellipse2DRenderCache;
  42394. })(BABYLON.ModelRenderCache);
  42395. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  42396. var Ellipse2DInstanceData = (function (_super) {
  42397. __extends(Ellipse2DInstanceData, _super);
  42398. function Ellipse2DInstanceData(partId) {
  42399. _super.call(this, partId, 1);
  42400. }
  42401. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  42402. get: function () {
  42403. return null;
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. __decorate([
  42409. BABYLON.instanceData()
  42410. ], Ellipse2DInstanceData.prototype, "properties", null);
  42411. return Ellipse2DInstanceData;
  42412. })(BABYLON.Shape2DInstanceData);
  42413. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  42414. var Ellipse2D = (function (_super) {
  42415. __extends(Ellipse2D, _super);
  42416. /**
  42417. * Create an Ellipse 2D Shape primitive
  42418. * @param settings a combination of settings, possible ones are
  42419. * - 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)
  42420. * - children: an array of direct children
  42421. * - id: a text identifier, for information purpose
  42422. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42423. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42424. * - scale: the initial scale of the primitive. default is 1
  42425. * - origin: define the normalized origin point location, default [0.5;0.5]
  42426. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  42427. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  42428. * - 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)
  42429. * - 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)
  42430. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42431. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42432. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42433. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42434. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42435. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42436. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42437. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42438. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42439. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42440. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42441. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42442. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42443. */
  42444. function Ellipse2D(settings) {
  42445. // Avoid checking every time if the object exists
  42446. if (settings == null) {
  42447. settings = {};
  42448. }
  42449. _super.call(this, settings);
  42450. if (settings.size != null) {
  42451. this.size = settings.size;
  42452. }
  42453. else if (settings.width || settings.height) {
  42454. var size = new BABYLON.Size(settings.width, settings.height);
  42455. this.size = size;
  42456. }
  42457. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  42458. this.subdivisions = sub;
  42459. }
  42460. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  42461. get: function () {
  42462. if (this._actualSize) {
  42463. return this._actualSize;
  42464. }
  42465. return this.size;
  42466. },
  42467. set: function (value) {
  42468. this._actualSize = value;
  42469. },
  42470. enumerable: true,
  42471. configurable: true
  42472. });
  42473. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  42474. get: function () {
  42475. return this._subdivisions;
  42476. },
  42477. set: function (value) {
  42478. this._subdivisions = value;
  42479. },
  42480. enumerable: true,
  42481. configurable: true
  42482. });
  42483. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  42484. var w = this.size.width / 2;
  42485. var h = this.size.height / 2;
  42486. var x = intersectInfo._localPickPosition.x - w;
  42487. var y = intersectInfo._localPickPosition.y - h;
  42488. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  42489. };
  42490. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  42491. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42492. };
  42493. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  42494. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  42495. return renderCache;
  42496. };
  42497. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42498. var renderCache = modelRenderCache;
  42499. var engine = this.owner.engine;
  42500. // Need to create WebGL resources for fill part?
  42501. if (this.fill) {
  42502. var vbSize = this.subdivisions + 1;
  42503. var vb = new Float32Array(vbSize);
  42504. for (var i = 0; i < vbSize; i++) {
  42505. vb[i] = i;
  42506. }
  42507. renderCache.fillVB = engine.createVertexBuffer(vb);
  42508. var triCount = vbSize - 1;
  42509. var ib = new Float32Array(triCount * 3);
  42510. for (var i = 0; i < triCount; i++) {
  42511. ib[i * 3 + 0] = 0;
  42512. ib[i * 3 + 2] = i + 1;
  42513. ib[i * 3 + 1] = i + 2;
  42514. }
  42515. ib[triCount * 3 - 2] = 1;
  42516. renderCache.fillIB = engine.createIndexBuffer(ib);
  42517. renderCache.fillIndicesCount = triCount * 3;
  42518. // 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
  42519. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  42520. if (ei) {
  42521. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  42522. }
  42523. // Get the non instanced version
  42524. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  42525. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  42526. }
  42527. // Need to create WebGL resource for border part?
  42528. if (this.border) {
  42529. var vbSize = this.subdivisions * 2;
  42530. var vb = new Float32Array(vbSize);
  42531. for (var i = 0; i < vbSize; i++) {
  42532. vb[i] = i;
  42533. }
  42534. renderCache.borderVB = engine.createVertexBuffer(vb);
  42535. var triCount = vbSize;
  42536. var rs = triCount / 2;
  42537. var ib = new Float32Array(triCount * 3);
  42538. for (var i = 0; i < rs; i++) {
  42539. var r0 = i;
  42540. var r1 = (i + 1) % rs;
  42541. ib[i * 6 + 0] = rs + r1;
  42542. ib[i * 6 + 1] = rs + r0;
  42543. ib[i * 6 + 2] = r0;
  42544. ib[i * 6 + 3] = r1;
  42545. ib[i * 6 + 4] = rs + r1;
  42546. ib[i * 6 + 5] = r0;
  42547. }
  42548. renderCache.borderIB = engine.createIndexBuffer(ib);
  42549. renderCache.borderIndicesCount = (triCount * 3);
  42550. // 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
  42551. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  42552. if (ei) {
  42553. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42554. }
  42555. // Get the non instanced version
  42556. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  42557. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42558. }
  42559. return renderCache;
  42560. };
  42561. Ellipse2D.prototype.createInstanceDataParts = function () {
  42562. var res = new Array();
  42563. if (this.border) {
  42564. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42565. }
  42566. if (this.fill) {
  42567. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42568. }
  42569. return res;
  42570. };
  42571. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  42572. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42573. return false;
  42574. }
  42575. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42576. var d = part;
  42577. var size = this.actualSize;
  42578. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  42579. }
  42580. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  42581. var d = part;
  42582. var size = this.actualSize;
  42583. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  42584. }
  42585. return true;
  42586. };
  42587. __decorate([
  42588. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  42589. ], Ellipse2D.prototype, "actualSize", null);
  42590. __decorate([
  42591. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  42592. ], Ellipse2D.prototype, "subdivisions", null);
  42593. Ellipse2D = __decorate([
  42594. BABYLON.className("Ellipse2D")
  42595. ], Ellipse2D);
  42596. return Ellipse2D;
  42597. })(BABYLON.Shape2D);
  42598. BABYLON.Ellipse2D = Ellipse2D;
  42599. })(BABYLON || (BABYLON = {}));
  42600. var BABYLON;
  42601. (function (BABYLON) {
  42602. var Sprite2DRenderCache = (function (_super) {
  42603. __extends(Sprite2DRenderCache, _super);
  42604. function Sprite2DRenderCache() {
  42605. _super.apply(this, arguments);
  42606. this.effectsReady = false;
  42607. this.vb = null;
  42608. this.ib = null;
  42609. this.instancingAttributes = null;
  42610. this.texture = null;
  42611. this.effect = null;
  42612. this.effectInstanced = null;
  42613. }
  42614. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  42615. // Do nothing if the shader is still loading/preparing
  42616. if (!this.effectsReady) {
  42617. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  42618. return false;
  42619. }
  42620. this.effectsReady = true;
  42621. }
  42622. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  42623. var engine = instanceInfo.owner.owner.engine;
  42624. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  42625. engine.enableEffect(effect);
  42626. effect.setTexture("diffuseSampler", this.texture);
  42627. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  42628. var cur = engine.getAlphaMode();
  42629. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42630. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42631. }
  42632. var pid = context.groupInfoPartData[0];
  42633. if (context.useInstancing) {
  42634. if (!this.instancingAttributes) {
  42635. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  42636. }
  42637. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  42638. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  42639. engine.unbindInstanceAttributes();
  42640. }
  42641. else {
  42642. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42643. this.setupUniforms(effect, 0, pid._partData, i);
  42644. engine.draw(true, 0, 6);
  42645. }
  42646. }
  42647. engine.setAlphaMode(cur);
  42648. return true;
  42649. };
  42650. Sprite2DRenderCache.prototype.dispose = function () {
  42651. if (!_super.prototype.dispose.call(this)) {
  42652. return false;
  42653. }
  42654. if (this.vb) {
  42655. this._engine._releaseBuffer(this.vb);
  42656. this.vb = null;
  42657. }
  42658. if (this.ib) {
  42659. this._engine._releaseBuffer(this.ib);
  42660. this.ib = null;
  42661. }
  42662. if (this.texture) {
  42663. this.texture.dispose();
  42664. this.texture = null;
  42665. }
  42666. if (this.effect) {
  42667. this._engine._releaseEffect(this.effect);
  42668. this.effect = null;
  42669. }
  42670. if (this.effectInstanced) {
  42671. this._engine._releaseEffect(this.effectInstanced);
  42672. this.effectInstanced = null;
  42673. }
  42674. return true;
  42675. };
  42676. return Sprite2DRenderCache;
  42677. })(BABYLON.ModelRenderCache);
  42678. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  42679. var Sprite2DInstanceData = (function (_super) {
  42680. __extends(Sprite2DInstanceData, _super);
  42681. function Sprite2DInstanceData(partId) {
  42682. _super.call(this, partId, 1);
  42683. }
  42684. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  42685. get: function () {
  42686. return null;
  42687. },
  42688. enumerable: true,
  42689. configurable: true
  42690. });
  42691. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  42692. get: function () {
  42693. return null;
  42694. },
  42695. enumerable: true,
  42696. configurable: true
  42697. });
  42698. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  42699. get: function () {
  42700. return null;
  42701. },
  42702. enumerable: true,
  42703. configurable: true
  42704. });
  42705. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  42706. // 3 floats being:
  42707. // - x: frame number to display
  42708. // - y: invertY setting
  42709. // - z: alignToPixel setting
  42710. get: function () {
  42711. return null;
  42712. },
  42713. enumerable: true,
  42714. configurable: true
  42715. });
  42716. __decorate([
  42717. BABYLON.instanceData()
  42718. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  42719. __decorate([
  42720. BABYLON.instanceData()
  42721. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  42722. __decorate([
  42723. BABYLON.instanceData()
  42724. ], Sprite2DInstanceData.prototype, "textureSize", null);
  42725. __decorate([
  42726. BABYLON.instanceData()
  42727. ], Sprite2DInstanceData.prototype, "properties", null);
  42728. return Sprite2DInstanceData;
  42729. })(BABYLON.InstanceDataBase);
  42730. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  42731. var Sprite2D = (function (_super) {
  42732. __extends(Sprite2D, _super);
  42733. /**
  42734. * Create an 2D Sprite primitive
  42735. * @param texture the texture that stores the sprite to render
  42736. * @param settings a combination of settings, possible ones are
  42737. * - 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)
  42738. * - children: an array of direct children
  42739. * - id a text identifier, for information purpose
  42740. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42741. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42742. * - scale: the initial scale of the primitive. default is 1
  42743. * - origin: define the normalized origin point location, default [0.5;0.5]
  42744. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  42745. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  42746. * - invertY: if true the texture Y will be inverted, default is false.
  42747. * - 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.
  42748. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  42749. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42750. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42751. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42752. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42753. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42754. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42755. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42756. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42757. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42758. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42759. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42760. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42761. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42762. */
  42763. function Sprite2D(texture, settings) {
  42764. if (!settings) {
  42765. settings = {};
  42766. }
  42767. _super.call(this, settings);
  42768. this.texture = texture;
  42769. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42770. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42771. this.size = settings.spriteSize;
  42772. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  42773. this.spriteFrame = 0;
  42774. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  42775. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  42776. this._isTransparent = true;
  42777. if (settings.spriteSize == null) {
  42778. var s = texture.getSize();
  42779. this.size = new BABYLON.Size(s.width, s.height);
  42780. }
  42781. }
  42782. Object.defineProperty(Sprite2D.prototype, "texture", {
  42783. get: function () {
  42784. return this._texture;
  42785. },
  42786. set: function (value) {
  42787. this._texture = value;
  42788. },
  42789. enumerable: true,
  42790. configurable: true
  42791. });
  42792. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  42793. get: function () {
  42794. if (this._actualSize) {
  42795. return this._actualSize;
  42796. }
  42797. return this.size;
  42798. },
  42799. set: function (value) {
  42800. this._actualSize = value;
  42801. },
  42802. enumerable: true,
  42803. configurable: true
  42804. });
  42805. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  42806. get: function () {
  42807. return this._location;
  42808. },
  42809. set: function (value) {
  42810. this._location = value;
  42811. },
  42812. enumerable: true,
  42813. configurable: true
  42814. });
  42815. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  42816. get: function () {
  42817. return this._spriteFrame;
  42818. },
  42819. set: function (value) {
  42820. this._spriteFrame = value;
  42821. },
  42822. enumerable: true,
  42823. configurable: true
  42824. });
  42825. Object.defineProperty(Sprite2D.prototype, "invertY", {
  42826. get: function () {
  42827. return this._invertY;
  42828. },
  42829. set: function (value) {
  42830. this._invertY = value;
  42831. },
  42832. enumerable: true,
  42833. configurable: true
  42834. });
  42835. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  42836. /**
  42837. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  42838. */
  42839. get: function () {
  42840. return this._alignToPixel;
  42841. },
  42842. set: function (value) {
  42843. this._alignToPixel = value;
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  42849. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  42850. };
  42851. /**
  42852. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  42853. */
  42854. Sprite2D.prototype.getAnimatables = function () {
  42855. var res = new Array();
  42856. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  42857. res.push(this.texture);
  42858. }
  42859. return res;
  42860. };
  42861. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  42862. // 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
  42863. return true;
  42864. };
  42865. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  42866. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  42867. return sprite;
  42868. };
  42869. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  42870. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  42871. return renderCache;
  42872. };
  42873. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42874. var renderCache = modelRenderCache;
  42875. var engine = this.owner.engine;
  42876. var vb = new Float32Array(4);
  42877. for (var i = 0; i < 4; i++) {
  42878. vb[i] = i;
  42879. }
  42880. renderCache.vb = engine.createVertexBuffer(vb);
  42881. var ib = new Float32Array(6);
  42882. ib[0] = 0;
  42883. ib[1] = 2;
  42884. ib[2] = 1;
  42885. ib[3] = 0;
  42886. ib[4] = 3;
  42887. ib[5] = 2;
  42888. renderCache.ib = engine.createIndexBuffer(ib);
  42889. renderCache.texture = this.texture;
  42890. // 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
  42891. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  42892. if (ei) {
  42893. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42894. }
  42895. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  42896. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  42897. return renderCache;
  42898. };
  42899. Sprite2D.prototype.createInstanceDataParts = function () {
  42900. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  42901. };
  42902. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  42903. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42904. return false;
  42905. }
  42906. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  42907. var d = this._instanceDataParts[0];
  42908. var ts = this.texture.getBaseSize();
  42909. var sl = this.spriteLocation;
  42910. var ss = this.actualSize;
  42911. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  42912. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  42913. d.sizeUV = suv;
  42914. Sprite2D._prop.x = this.spriteFrame;
  42915. Sprite2D._prop.y = this.invertY ? 1 : 0;
  42916. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  42917. d.properties = Sprite2D._prop;
  42918. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  42919. }
  42920. return true;
  42921. };
  42922. Sprite2D.SPRITE2D_MAINPARTID = 1;
  42923. Sprite2D._prop = BABYLON.Vector3.Zero();
  42924. __decorate([
  42925. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  42926. ], Sprite2D.prototype, "texture", null);
  42927. __decorate([
  42928. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  42929. ], Sprite2D.prototype, "actualSize", null);
  42930. __decorate([
  42931. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  42932. ], Sprite2D.prototype, "spriteLocation", null);
  42933. __decorate([
  42934. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  42935. ], Sprite2D.prototype, "spriteFrame", null);
  42936. __decorate([
  42937. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  42938. ], Sprite2D.prototype, "invertY", null);
  42939. Sprite2D = __decorate([
  42940. BABYLON.className("Sprite2D")
  42941. ], Sprite2D);
  42942. return Sprite2D;
  42943. })(BABYLON.RenderablePrim2D);
  42944. BABYLON.Sprite2D = Sprite2D;
  42945. })(BABYLON || (BABYLON = {}));
  42946. var BABYLON;
  42947. (function (BABYLON) {
  42948. var Text2DRenderCache = (function (_super) {
  42949. __extends(Text2DRenderCache, _super);
  42950. function Text2DRenderCache() {
  42951. _super.apply(this, arguments);
  42952. this.effectsReady = false;
  42953. this.vb = null;
  42954. this.ib = null;
  42955. this.instancingAttributes = null;
  42956. this.fontTexture = null;
  42957. this.effect = null;
  42958. this.effectInstanced = null;
  42959. }
  42960. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  42961. // Do nothing if the shader is still loading/preparing
  42962. if (!this.effectsReady) {
  42963. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  42964. return false;
  42965. }
  42966. this.effectsReady = true;
  42967. }
  42968. var engine = instanceInfo.owner.owner.engine;
  42969. this.fontTexture.update();
  42970. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  42971. engine.enableEffect(effect);
  42972. effect.setTexture("diffuseSampler", this.fontTexture);
  42973. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  42974. var curAlphaMode = engine.getAlphaMode();
  42975. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  42976. var pid = context.groupInfoPartData[0];
  42977. if (context.useInstancing) {
  42978. if (!this.instancingAttributes) {
  42979. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  42980. }
  42981. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  42982. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  42983. engine.unbindInstanceAttributes();
  42984. }
  42985. else {
  42986. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42987. this.setupUniforms(effect, 0, pid._partData, i);
  42988. engine.draw(true, 0, 6);
  42989. }
  42990. }
  42991. engine.setAlphaMode(curAlphaMode);
  42992. return true;
  42993. };
  42994. Text2DRenderCache.prototype.dispose = function () {
  42995. if (!_super.prototype.dispose.call(this)) {
  42996. return false;
  42997. }
  42998. if (this.vb) {
  42999. this._engine._releaseBuffer(this.vb);
  43000. this.vb = null;
  43001. }
  43002. if (this.ib) {
  43003. this._engine._releaseBuffer(this.ib);
  43004. this.ib = null;
  43005. }
  43006. if (this.fontTexture) {
  43007. this.fontTexture.dispose();
  43008. this.fontTexture = null;
  43009. }
  43010. if (this.effect) {
  43011. this._engine._releaseEffect(this.effect);
  43012. this.effect = null;
  43013. }
  43014. if (this.effectInstanced) {
  43015. this._engine._releaseEffect(this.effectInstanced);
  43016. this.effectInstanced = null;
  43017. }
  43018. return true;
  43019. };
  43020. return Text2DRenderCache;
  43021. })(BABYLON.ModelRenderCache);
  43022. BABYLON.Text2DRenderCache = Text2DRenderCache;
  43023. var Text2DInstanceData = (function (_super) {
  43024. __extends(Text2DInstanceData, _super);
  43025. function Text2DInstanceData(partId, dataElementCount) {
  43026. _super.call(this, partId, dataElementCount);
  43027. }
  43028. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  43029. get: function () {
  43030. return null;
  43031. },
  43032. enumerable: true,
  43033. configurable: true
  43034. });
  43035. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  43036. get: function () {
  43037. return null;
  43038. },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  43043. get: function () {
  43044. return null;
  43045. },
  43046. enumerable: true,
  43047. configurable: true
  43048. });
  43049. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  43050. get: function () {
  43051. return null;
  43052. },
  43053. enumerable: true,
  43054. configurable: true
  43055. });
  43056. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  43057. get: function () {
  43058. return null;
  43059. },
  43060. enumerable: true,
  43061. configurable: true
  43062. });
  43063. __decorate([
  43064. BABYLON.instanceData()
  43065. ], Text2DInstanceData.prototype, "topLeftUV", null);
  43066. __decorate([
  43067. BABYLON.instanceData()
  43068. ], Text2DInstanceData.prototype, "sizeUV", null);
  43069. __decorate([
  43070. BABYLON.instanceData()
  43071. ], Text2DInstanceData.prototype, "textureSize", null);
  43072. __decorate([
  43073. BABYLON.instanceData()
  43074. ], Text2DInstanceData.prototype, "color", null);
  43075. __decorate([
  43076. BABYLON.instanceData()
  43077. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  43078. return Text2DInstanceData;
  43079. })(BABYLON.InstanceDataBase);
  43080. BABYLON.Text2DInstanceData = Text2DInstanceData;
  43081. var Text2D = (function (_super) {
  43082. __extends(Text2D, _super);
  43083. /**
  43084. * Create a Text primitive
  43085. * @param text the text to display
  43086. * @param settings a combination of settings, possible ones are
  43087. * - 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)
  43088. * - children: an array of direct children
  43089. * - id a text identifier, for information purpose
  43090. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43091. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43092. * - scale: the initial scale of the primitive. default is 1
  43093. * - origin: define the normalized origin point location, default [0.5;0.5]
  43094. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  43095. * - 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.
  43096. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  43097. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  43098. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  43099. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  43100. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43101. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43102. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43103. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43104. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43105. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43106. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43107. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43108. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43109. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43110. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43111. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43112. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43113. */
  43114. function Text2D(text, settings) {
  43115. if (!settings) {
  43116. settings = {};
  43117. }
  43118. _super.call(this, settings);
  43119. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  43120. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  43121. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  43122. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  43123. this._textSize = null;
  43124. this.text = text;
  43125. this.size = (settings.size == null) ? null : settings.size;
  43126. this.isAlphaTest = true;
  43127. }
  43128. Object.defineProperty(Text2D.prototype, "fontName", {
  43129. get: function () {
  43130. return this._fontName;
  43131. },
  43132. set: function (value) {
  43133. if (this._fontName) {
  43134. throw new Error("Font Name change is not supported right now.");
  43135. }
  43136. this._fontName = value;
  43137. },
  43138. enumerable: true,
  43139. configurable: true
  43140. });
  43141. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  43142. get: function () {
  43143. return this._defaultFontColor;
  43144. },
  43145. set: function (value) {
  43146. this._defaultFontColor = value;
  43147. },
  43148. enumerable: true,
  43149. configurable: true
  43150. });
  43151. Object.defineProperty(Text2D.prototype, "text", {
  43152. get: function () {
  43153. return this._text;
  43154. },
  43155. set: function (value) {
  43156. this._text = value;
  43157. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  43158. this._size = null;
  43159. this._updateCharCount();
  43160. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  43161. var s = this.textSize;
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. Object.defineProperty(Text2D.prototype, "size", {
  43167. get: function () {
  43168. if (this._size != null) {
  43169. return this._size;
  43170. }
  43171. return this.textSize;
  43172. },
  43173. set: function (value) {
  43174. this._size = value;
  43175. },
  43176. enumerable: true,
  43177. configurable: true
  43178. });
  43179. Object.defineProperty(Text2D.prototype, "actualSize", {
  43180. /**
  43181. * Get the actual size of the Text2D primitive
  43182. */
  43183. get: function () {
  43184. if (this._actualSize) {
  43185. return this._actualSize;
  43186. }
  43187. return this.size;
  43188. },
  43189. enumerable: true,
  43190. configurable: true
  43191. });
  43192. Object.defineProperty(Text2D.prototype, "textSize", {
  43193. /**
  43194. * Get the area that bounds the text associated to the primitive
  43195. */
  43196. get: function () {
  43197. if (!this._textSize) {
  43198. if (this.owner) {
  43199. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  43200. if (!newSize.equals(this._textSize)) {
  43201. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  43202. this._positioningDirty();
  43203. }
  43204. this._textSize = newSize;
  43205. }
  43206. else {
  43207. return Text2D.nullSize;
  43208. }
  43209. }
  43210. return this._textSize;
  43211. },
  43212. enumerable: true,
  43213. configurable: true
  43214. });
  43215. Object.defineProperty(Text2D.prototype, "fontTexture", {
  43216. get: function () {
  43217. if (this._fontTexture) {
  43218. return this._fontTexture;
  43219. }
  43220. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  43221. return this._fontTexture;
  43222. },
  43223. enumerable: true,
  43224. configurable: true
  43225. });
  43226. /**
  43227. * Dispose the primitive, remove it from its parent
  43228. */
  43229. Text2D.prototype.dispose = function () {
  43230. if (!_super.prototype.dispose.call(this)) {
  43231. return false;
  43232. }
  43233. if (this._fontTexture) {
  43234. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  43235. this._fontTexture = null;
  43236. }
  43237. return true;
  43238. };
  43239. Text2D.prototype.updateLevelBoundingInfo = function () {
  43240. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43241. };
  43242. Text2D.prototype.levelIntersect = function (intersectInfo) {
  43243. // 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...
  43244. return true;
  43245. };
  43246. Text2D.prototype.createModelRenderCache = function (modelKey) {
  43247. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  43248. return renderCache;
  43249. };
  43250. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43251. var renderCache = modelRenderCache;
  43252. var engine = this.owner.engine;
  43253. renderCache.fontTexture = this.fontTexture;
  43254. var vb = new Float32Array(4);
  43255. for (var i = 0; i < 4; i++) {
  43256. vb[i] = i;
  43257. }
  43258. renderCache.vb = engine.createVertexBuffer(vb);
  43259. var ib = new Float32Array(6);
  43260. ib[0] = 0;
  43261. ib[1] = 2;
  43262. ib[2] = 1;
  43263. ib[3] = 0;
  43264. ib[4] = 3;
  43265. ib[5] = 2;
  43266. renderCache.ib = engine.createIndexBuffer(ib);
  43267. // 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
  43268. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  43269. if (ei) {
  43270. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43271. }
  43272. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  43273. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43274. return renderCache;
  43275. };
  43276. Text2D.prototype.createInstanceDataParts = function () {
  43277. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  43278. };
  43279. // Looks like a hack!? Yes! Because that's what it is!
  43280. // 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
  43281. // 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)
  43282. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43283. if (!this._charCount) {
  43284. var curText = this._text;
  43285. this.text = "A";
  43286. return curText;
  43287. }
  43288. };
  43289. // if obj contains something, we restore the _text property
  43290. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43291. if (obj !== undefined) {
  43292. this.text = obj;
  43293. }
  43294. };
  43295. Text2D.prototype.refreshInstanceDataPart = function (part) {
  43296. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43297. return false;
  43298. }
  43299. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  43300. var d = part;
  43301. var texture = this.fontTexture;
  43302. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  43303. var ts = texture.getSize();
  43304. var offset = BABYLON.Vector2.Zero();
  43305. var lh = this.fontTexture.lineHeight;
  43306. 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
  43307. var charxpos = 0;
  43308. d.dataElementCount = this._charCount;
  43309. d.curElement = 0;
  43310. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  43311. var char = _a[_i];
  43312. // Line feed
  43313. if (char === "\n") {
  43314. offset.x = 0;
  43315. offset.y -= texture.lineHeight;
  43316. }
  43317. // Tabulation ?
  43318. if (char === "\t") {
  43319. var nextPos = charxpos + this._tabulationSize;
  43320. nextPos = nextPos - (nextPos % this._tabulationSize);
  43321. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  43322. charxpos = nextPos;
  43323. continue;
  43324. }
  43325. if (char < " ") {
  43326. continue;
  43327. }
  43328. this.updateInstanceDataPart(d, offset);
  43329. var ci = texture.getChar(char);
  43330. offset.x += ci.charWidth;
  43331. d.topLeftUV = ci.topLeftUV;
  43332. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  43333. d.sizeUV = suv;
  43334. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43335. d.color = this.defaultFontColor;
  43336. d.superSampleFactor = superSampleFactor;
  43337. ++d.curElement;
  43338. }
  43339. }
  43340. return true;
  43341. };
  43342. Text2D.prototype._updateCharCount = function () {
  43343. var count = 0;
  43344. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  43345. var char = _a[_i];
  43346. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  43347. continue;
  43348. }
  43349. ++count;
  43350. }
  43351. this._charCount = count;
  43352. };
  43353. Text2D.TEXT2D_MAINPARTID = 1;
  43354. __decorate([
  43355. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  43356. ], Text2D.prototype, "fontName", null);
  43357. __decorate([
  43358. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  43359. ], Text2D.prototype, "defaultFontColor", null);
  43360. __decorate([
  43361. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  43362. ], Text2D.prototype, "text", null);
  43363. __decorate([
  43364. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  43365. ], Text2D.prototype, "size", null);
  43366. Text2D = __decorate([
  43367. BABYLON.className("Text2D")
  43368. ], Text2D);
  43369. return Text2D;
  43370. })(BABYLON.RenderablePrim2D);
  43371. BABYLON.Text2D = Text2D;
  43372. })(BABYLON || (BABYLON = {}));
  43373. var BABYLON;
  43374. (function (BABYLON) {
  43375. var Lines2DRenderCache = (function (_super) {
  43376. __extends(Lines2DRenderCache, _super);
  43377. function Lines2DRenderCache(engine, modelKey) {
  43378. _super.call(this, engine, modelKey);
  43379. this.effectsReady = false;
  43380. this.fillVB = null;
  43381. this.fillIB = null;
  43382. this.fillIndicesCount = 0;
  43383. this.instancingFillAttributes = null;
  43384. this.effectFill = null;
  43385. this.effectFillInstanced = null;
  43386. this.borderVB = null;
  43387. this.borderIB = null;
  43388. this.borderIndicesCount = 0;
  43389. this.instancingBorderAttributes = null;
  43390. this.effectBorder = null;
  43391. this.effectBorderInstanced = null;
  43392. }
  43393. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  43394. // Do nothing if the shader is still loading/preparing
  43395. if (!this.effectsReady) {
  43396. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43397. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43398. return false;
  43399. }
  43400. this.effectsReady = true;
  43401. }
  43402. var engine = instanceInfo.owner.owner.engine;
  43403. var depthFunction = 0;
  43404. if (this.effectFill && this.effectBorder) {
  43405. depthFunction = engine.getDepthFunction();
  43406. engine.setDepthFunctionToLessOrEqual();
  43407. }
  43408. var curAlphaMode = engine.getAlphaMode();
  43409. if (this.effectFill) {
  43410. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43411. var pid = context.groupInfoPartData[partIndex];
  43412. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43413. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43414. }
  43415. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43416. engine.enableEffect(effect);
  43417. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  43418. if (context.useInstancing) {
  43419. if (!this.instancingFillAttributes) {
  43420. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43421. }
  43422. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  43423. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  43424. engine.unbindInstanceAttributes();
  43425. }
  43426. else {
  43427. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43428. this.setupUniforms(effect, partIndex, pid._partData, i);
  43429. engine.draw(true, 0, this.fillIndicesCount);
  43430. }
  43431. }
  43432. }
  43433. if (this.effectBorder) {
  43434. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43435. var pid = context.groupInfoPartData[partIndex];
  43436. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43437. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43438. }
  43439. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43440. engine.enableEffect(effect);
  43441. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  43442. if (context.useInstancing) {
  43443. if (!this.instancingBorderAttributes) {
  43444. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43445. }
  43446. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  43447. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  43448. engine.unbindInstanceAttributes();
  43449. }
  43450. else {
  43451. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43452. this.setupUniforms(effect, partIndex, pid._partData, i);
  43453. engine.draw(true, 0, this.borderIndicesCount);
  43454. }
  43455. }
  43456. }
  43457. engine.setAlphaMode(curAlphaMode);
  43458. if (this.effectFill && this.effectBorder) {
  43459. engine.setDepthFunction(depthFunction);
  43460. }
  43461. return true;
  43462. };
  43463. Lines2DRenderCache.prototype.dispose = function () {
  43464. if (!_super.prototype.dispose.call(this)) {
  43465. return false;
  43466. }
  43467. if (this.fillVB) {
  43468. this._engine._releaseBuffer(this.fillVB);
  43469. this.fillVB = null;
  43470. }
  43471. if (this.fillIB) {
  43472. this._engine._releaseBuffer(this.fillIB);
  43473. this.fillIB = null;
  43474. }
  43475. if (this.effectFill) {
  43476. this._engine._releaseEffect(this.effectFill);
  43477. this.effectFill = null;
  43478. }
  43479. if (this.effectFillInstanced) {
  43480. this._engine._releaseEffect(this.effectFillInstanced);
  43481. this.effectFillInstanced = null;
  43482. }
  43483. if (this.borderVB) {
  43484. this._engine._releaseBuffer(this.borderVB);
  43485. this.borderVB = null;
  43486. }
  43487. if (this.borderIB) {
  43488. this._engine._releaseBuffer(this.borderIB);
  43489. this.borderIB = null;
  43490. }
  43491. if (this.effectBorder) {
  43492. this._engine._releaseEffect(this.effectBorder);
  43493. this.effectBorder = null;
  43494. }
  43495. if (this.effectBorderInstanced) {
  43496. this._engine._releaseEffect(this.effectBorderInstanced);
  43497. this.effectBorderInstanced = null;
  43498. }
  43499. return true;
  43500. };
  43501. return Lines2DRenderCache;
  43502. })(BABYLON.ModelRenderCache);
  43503. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  43504. var Lines2DInstanceData = (function (_super) {
  43505. __extends(Lines2DInstanceData, _super);
  43506. function Lines2DInstanceData(partId) {
  43507. _super.call(this, partId, 1);
  43508. }
  43509. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  43510. get: function () {
  43511. return null;
  43512. },
  43513. enumerable: true,
  43514. configurable: true
  43515. });
  43516. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  43517. get: function () {
  43518. return null;
  43519. },
  43520. enumerable: true,
  43521. configurable: true
  43522. });
  43523. __decorate([
  43524. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43525. ], Lines2DInstanceData.prototype, "boundingMin", null);
  43526. __decorate([
  43527. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43528. ], Lines2DInstanceData.prototype, "boundingMax", null);
  43529. return Lines2DInstanceData;
  43530. })(BABYLON.Shape2DInstanceData);
  43531. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  43532. var Lines2D = (function (_super) {
  43533. __extends(Lines2D, _super);
  43534. /**
  43535. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  43536. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  43537. * @param settings a combination of settings, possible ones are
  43538. * - 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)
  43539. * - children: an array of direct children
  43540. * - id a text identifier, for information purpose
  43541. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43542. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43543. * - scale: the initial scale of the primitive. default is 1
  43544. * - origin: define the normalized origin point location, default [0.5;0.5]
  43545. * - 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.
  43546. * - 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.
  43547. * - 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.
  43548. * - 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.
  43549. * - 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)
  43550. * - 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)
  43551. * - borderThickness: the thickness of the drawn border, default is 1.
  43552. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  43553. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43554. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43555. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43556. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43557. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43558. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43559. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43560. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43561. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43562. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43563. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43564. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43565. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43566. */
  43567. function Lines2D(points, settings) {
  43568. if (!settings) {
  43569. settings = {};
  43570. }
  43571. _super.call(this, settings);
  43572. this._fillVB = null;
  43573. this._fillIB = null;
  43574. this._borderVB = null;
  43575. this._borderIB = null;
  43576. this._size = BABYLON.Size.Zero();
  43577. this._boundingMin = null;
  43578. this._boundingMax = null;
  43579. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  43580. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  43581. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  43582. var closed = (settings.closed == null) ? false : settings.closed;
  43583. this.points = points;
  43584. this.fillThickness = fillThickness;
  43585. this.startCap = startCap;
  43586. this.endCap = endCap;
  43587. this.closed = closed;
  43588. }
  43589. Object.defineProperty(Lines2D, "NoCap", {
  43590. /**
  43591. * No Cap to apply on the extremity
  43592. */
  43593. get: function () { return Lines2D._noCap; },
  43594. enumerable: true,
  43595. configurable: true
  43596. });
  43597. Object.defineProperty(Lines2D, "RoundCap", {
  43598. /**
  43599. * A round cap, will use the line thickness as diameter
  43600. */
  43601. get: function () { return Lines2D._roundCap; },
  43602. enumerable: true,
  43603. configurable: true
  43604. });
  43605. Object.defineProperty(Lines2D, "TriangleCap", {
  43606. /**
  43607. * Creates a triangle at the extremity.
  43608. */
  43609. get: function () { return Lines2D._triangleCap; },
  43610. enumerable: true,
  43611. configurable: true
  43612. });
  43613. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  43614. /**
  43615. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  43616. */
  43617. get: function () { return Lines2D._squareAnchorCap; },
  43618. enumerable: true,
  43619. configurable: true
  43620. });
  43621. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  43622. /**
  43623. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  43624. */
  43625. get: function () { return Lines2D._roundAnchorCap; },
  43626. enumerable: true,
  43627. configurable: true
  43628. });
  43629. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  43630. /**
  43631. * Creates a diamond anchor at the extremity.
  43632. */
  43633. get: function () { return Lines2D._diamondAnchorCap; },
  43634. enumerable: true,
  43635. configurable: true
  43636. });
  43637. Object.defineProperty(Lines2D, "ArrowCap", {
  43638. /**
  43639. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  43640. */
  43641. get: function () { return Lines2D._arrowCap; },
  43642. enumerable: true,
  43643. configurable: true
  43644. });
  43645. Object.defineProperty(Lines2D.prototype, "points", {
  43646. get: function () {
  43647. return this._points;
  43648. },
  43649. set: function (value) {
  43650. this._points = value;
  43651. this._boundingBoxDirty();
  43652. },
  43653. enumerable: true,
  43654. configurable: true
  43655. });
  43656. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  43657. get: function () {
  43658. return this._fillThickness;
  43659. },
  43660. set: function (value) {
  43661. this._fillThickness = value;
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. Object.defineProperty(Lines2D.prototype, "closed", {
  43667. get: function () {
  43668. return this._closed;
  43669. },
  43670. set: function (value) {
  43671. this._closed = value;
  43672. },
  43673. enumerable: true,
  43674. configurable: true
  43675. });
  43676. Object.defineProperty(Lines2D.prototype, "startCap", {
  43677. get: function () {
  43678. return this._startCap;
  43679. },
  43680. set: function (value) {
  43681. this._startCap = value;
  43682. },
  43683. enumerable: true,
  43684. configurable: true
  43685. });
  43686. Object.defineProperty(Lines2D.prototype, "endCap", {
  43687. get: function () {
  43688. return this._endCap;
  43689. },
  43690. set: function (value) {
  43691. this._endCap = value;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  43697. var _this = this;
  43698. if (this._contour == null) {
  43699. this._computeLines2D();
  43700. }
  43701. var pl = this.points.length;
  43702. var l = this.closed ? pl + 1 : pl;
  43703. var p = intersectInfo._localPickPosition;
  43704. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  43705. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  43706. for (var i = 1; i < l; i++) {
  43707. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  43708. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  43709. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  43710. return true;
  43711. }
  43712. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  43713. return true;
  43714. }
  43715. Lines2D._prevA.x = Lines2D._curA.x;
  43716. Lines2D._prevA.y = Lines2D._curA.y;
  43717. Lines2D._prevB.x = Lines2D._curB.x;
  43718. Lines2D._prevB.y = Lines2D._curB.y;
  43719. }
  43720. var capIntersect = function (tri, points) {
  43721. var l = tri.length;
  43722. for (var i = 0; i < l; i += 3) {
  43723. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  43724. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  43725. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  43726. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  43727. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  43728. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  43729. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  43730. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  43731. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  43732. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  43733. return true;
  43734. }
  43735. }
  43736. return false;
  43737. };
  43738. if (this._startCapTriIndices) {
  43739. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  43740. return true;
  43741. }
  43742. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  43743. return true;
  43744. }
  43745. }
  43746. return false;
  43747. };
  43748. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  43749. get: function () {
  43750. if (!this._boundingMin) {
  43751. this._computeLines2D();
  43752. }
  43753. return this._boundingMin;
  43754. },
  43755. enumerable: true,
  43756. configurable: true
  43757. });
  43758. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  43759. get: function () {
  43760. if (!this._boundingMax) {
  43761. this._computeLines2D();
  43762. }
  43763. return this._boundingMax;
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  43769. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43770. // Remove the BORDER category, we don't use it in the VertexShader
  43771. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  43772. if (i !== -1) {
  43773. res.splice(i, 1);
  43774. }
  43775. return res;
  43776. };
  43777. Lines2D.prototype.updateLevelBoundingInfo = function () {
  43778. if (!this._boundingMin) {
  43779. this._computeLines2D();
  43780. }
  43781. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  43782. };
  43783. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  43784. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  43785. return renderCache;
  43786. };
  43787. ///////////////////////////////////////////////////////////////////////////////////
  43788. // Methods for Lines building
  43789. Lines2D.prototype._perp = function (v, res) {
  43790. res.x = v.y;
  43791. res.y = -v.x;
  43792. };
  43793. ;
  43794. Lines2D.prototype._direction = function (a, b, res) {
  43795. a.subtractToRef(b, res);
  43796. res.normalize();
  43797. };
  43798. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  43799. a.addToRef(b, tangent);
  43800. tangent.normalize();
  43801. miter.x = -tangent.y;
  43802. miter.y = tangent.x;
  43803. Lines2D._miterTps.x = -a.y;
  43804. Lines2D._miterTps.y = a.x;
  43805. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  43806. };
  43807. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  43808. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  43809. if (d === 0)
  43810. return false;
  43811. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  43812. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  43813. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  43814. return false;
  43815. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  43816. return false;
  43817. return true;
  43818. };
  43819. Lines2D.prototype._updateMinMax = function (array, offset) {
  43820. if (offset >= array.length) {
  43821. return;
  43822. }
  43823. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  43824. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  43825. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  43826. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  43827. };
  43828. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  43829. var borderMode = borderThickness != null && !isNaN(borderThickness);
  43830. var off = index * (borderMode ? 8 : 4);
  43831. // 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)
  43832. if (off >= array.length) {
  43833. return;
  43834. }
  43835. // Store start/end normal, we need it for the cap construction
  43836. if (index === 0) {
  43837. this._perp(n, Lines2D._startDir);
  43838. }
  43839. else if (index === max - 1) {
  43840. this._perp(n, Lines2D._endDir);
  43841. Lines2D._endDir.x *= -1;
  43842. Lines2D._endDir.y *= -1;
  43843. }
  43844. var swap = false;
  43845. array[off + 0] = p.x + n.x * halfThickness;
  43846. array[off + 1] = p.y + n.y * halfThickness;
  43847. array[off + 2] = p.x + n.x * -halfThickness;
  43848. array[off + 3] = p.y + n.y * -halfThickness;
  43849. this._updateMinMax(array, off);
  43850. this._updateMinMax(array, off + 2);
  43851. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  43852. // 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
  43853. if (detectFlip !== undefined) {
  43854. // Flip if intersect
  43855. var flipOff = detectFlip * (borderMode ? 8 : 4);
  43856. 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])) {
  43857. swap = true;
  43858. var tps = array[off + 0];
  43859. array[off + 0] = array[off + 2];
  43860. array[off + 2] = tps;
  43861. tps = array[off + 1];
  43862. array[off + 1] = array[off + 3];
  43863. array[off + 3] = tps;
  43864. }
  43865. }
  43866. if (borderMode) {
  43867. var t = halfThickness + borderThickness;
  43868. array[off + 4] = p.x + n.x * (swap ? -t : t);
  43869. array[off + 5] = p.y + n.y * (swap ? -t : t);
  43870. array[off + 6] = p.x + n.x * (swap ? t : -t);
  43871. array[off + 7] = p.y + n.y * (swap ? t : -t);
  43872. this._updateMinMax(array, off + 4);
  43873. this._updateMinMax(array, off + 6);
  43874. }
  43875. if (contour) {
  43876. off += borderMode ? 4 : 0;
  43877. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  43878. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  43879. }
  43880. };
  43881. Lines2D.prototype._getCapSize = function (type, border) {
  43882. if (border === void 0) { border = false; }
  43883. var sd = Lines2D._roundCapSubDiv;
  43884. // If no array given, we call this to get the size
  43885. var vbsize = 0, ibsize = 0;
  43886. switch (type) {
  43887. case Lines2D.NoCap:
  43888. {
  43889. // If the line is not close and we're computing border, we add the size to generate the edge border
  43890. if (!this.closed && border) {
  43891. vbsize = 4;
  43892. ibsize = 6;
  43893. }
  43894. else {
  43895. vbsize = ibsize = 0;
  43896. }
  43897. break;
  43898. }
  43899. case Lines2D.RoundCap:
  43900. {
  43901. if (border) {
  43902. vbsize = sd;
  43903. ibsize = (sd - 2) * 3;
  43904. }
  43905. else {
  43906. vbsize = (sd / 2) + 1;
  43907. ibsize = (sd / 2) * 3;
  43908. }
  43909. break;
  43910. }
  43911. case Lines2D.ArrowCap:
  43912. {
  43913. if (border) {
  43914. vbsize = 12;
  43915. ibsize = 24;
  43916. }
  43917. else {
  43918. vbsize = 3;
  43919. ibsize = 3;
  43920. }
  43921. break;
  43922. }
  43923. case Lines2D.TriangleCap:
  43924. {
  43925. if (border) {
  43926. vbsize = 6;
  43927. ibsize = 12;
  43928. }
  43929. else {
  43930. vbsize = 3;
  43931. ibsize = 3;
  43932. }
  43933. break;
  43934. }
  43935. case Lines2D.DiamondAnchorCap:
  43936. {
  43937. if (border) {
  43938. vbsize = 10;
  43939. ibsize = 24;
  43940. }
  43941. else {
  43942. vbsize = 5;
  43943. ibsize = 9;
  43944. }
  43945. break;
  43946. }
  43947. case Lines2D.SquareAnchorCap:
  43948. {
  43949. if (border) {
  43950. vbsize = 12;
  43951. ibsize = 30;
  43952. }
  43953. else {
  43954. vbsize = 4;
  43955. ibsize = 6;
  43956. }
  43957. break;
  43958. }
  43959. case Lines2D.RoundAnchorCap:
  43960. {
  43961. if (border) {
  43962. vbsize = sd * 2;
  43963. ibsize = (sd - 1) * 6;
  43964. }
  43965. else {
  43966. vbsize = sd + 1;
  43967. ibsize = (sd + 1) * 3;
  43968. }
  43969. break;
  43970. }
  43971. }
  43972. return { vbsize: vbsize * 2, ibsize: ibsize };
  43973. };
  43974. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  43975. var c = Math.cos(rotation);
  43976. var s = Math.sin(rotation);
  43977. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  43978. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  43979. var offset = baseOffset + (index * 2);
  43980. vb[offset + 0] = Lines2D._tpsV.x;
  43981. vb[offset + 1] = Lines2D._tpsV.y;
  43982. if (contour) {
  43983. contour.push(Lines2D._tpsV.x);
  43984. contour.push(Lines2D._tpsV.y);
  43985. }
  43986. this._updateMinMax(vb, offset);
  43987. return (baseOffset + index * 2) / 2;
  43988. };
  43989. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  43990. ib[baseOffset + index] = vertexIndex;
  43991. };
  43992. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  43993. // 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
  43994. var sd = Lines2D._roundCapSubDiv;
  43995. var dir = new BABYLON.Vector2(1, 0);
  43996. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  43997. var ht = thickness / 2;
  43998. var t = thickness;
  43999. var borderMode = borderThickness != null;
  44000. var bt = borderThickness;
  44001. switch (type) {
  44002. case Lines2D.NoCap:
  44003. if (borderMode && !this.closed) {
  44004. var vi = 0;
  44005. var ii = 0;
  44006. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  44007. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  44008. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  44009. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  44010. this._storeIndex(ib, ibi, ii++, v1);
  44011. this._storeIndex(ib, ibi, ii++, v2);
  44012. this._storeIndex(ib, ibi, ii++, v3);
  44013. this._storeIndex(ib, ibi, ii++, v1);
  44014. this._storeIndex(ib, ibi, ii++, v3);
  44015. this._storeIndex(ib, ibi, ii++, v4);
  44016. }
  44017. break;
  44018. case Lines2D.ArrowCap:
  44019. ht *= 2;
  44020. case Lines2D.TriangleCap:
  44021. {
  44022. if (borderMode) {
  44023. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  44024. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  44025. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  44026. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  44027. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  44028. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  44029. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  44030. var ii = 0;
  44031. this._storeIndex(ib, ibi, ii++, v1);
  44032. this._storeIndex(ib, ibi, ii++, v4);
  44033. this._storeIndex(ib, ibi, ii++, v5);
  44034. this._storeIndex(ib, ibi, ii++, v1);
  44035. this._storeIndex(ib, ibi, ii++, v5);
  44036. this._storeIndex(ib, ibi, ii++, v2);
  44037. this._storeIndex(ib, ibi, ii++, v6);
  44038. this._storeIndex(ib, ibi, ii++, v3);
  44039. this._storeIndex(ib, ibi, ii++, v2);
  44040. this._storeIndex(ib, ibi, ii++, v6);
  44041. this._storeIndex(ib, ibi, ii++, v2);
  44042. this._storeIndex(ib, ibi, ii++, v5);
  44043. if (type === Lines2D.ArrowCap) {
  44044. var rht = thickness / 2;
  44045. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  44046. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  44047. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  44048. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  44049. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  44050. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  44051. this._storeIndex(ib, ibi, ii++, v7);
  44052. this._storeIndex(ib, ibi, ii++, v8);
  44053. this._storeIndex(ib, ibi, ii++, v9);
  44054. this._storeIndex(ib, ibi, ii++, v7);
  44055. this._storeIndex(ib, ibi, ii++, v9);
  44056. this._storeIndex(ib, ibi, ii++, v4);
  44057. this._storeIndex(ib, ibi, ii++, v10);
  44058. this._storeIndex(ib, ibi, ii++, v12);
  44059. this._storeIndex(ib, ibi, ii++, v11);
  44060. this._storeIndex(ib, ibi, ii++, v10);
  44061. this._storeIndex(ib, ibi, ii++, v6);
  44062. this._storeIndex(ib, ibi, ii++, v12);
  44063. }
  44064. }
  44065. else {
  44066. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  44067. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  44068. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  44069. this._storeIndex(ib, ibi, 0, v1);
  44070. this._storeIndex(ib, ibi, 1, v2);
  44071. this._storeIndex(ib, ibi, 2, v3);
  44072. }
  44073. break;
  44074. }
  44075. case Lines2D.RoundCap:
  44076. {
  44077. if (borderMode) {
  44078. var curA = -Math.PI / 2;
  44079. var incA = Math.PI / (sd / 2 - 1);
  44080. var ii = 0;
  44081. for (var i = 0; i < (sd / 2); i++) {
  44082. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44083. 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);
  44084. if (i > 0) {
  44085. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44086. this._storeIndex(ib, ibi, ii++, v2 - 2);
  44087. this._storeIndex(ib, ibi, ii++, v2);
  44088. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44089. this._storeIndex(ib, ibi, ii++, v2);
  44090. this._storeIndex(ib, ibi, ii++, v1);
  44091. }
  44092. curA += incA;
  44093. }
  44094. }
  44095. else {
  44096. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  44097. var curA = -Math.PI / 2;
  44098. var incA = Math.PI / (sd / 2 - 1);
  44099. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44100. curA += incA;
  44101. for (var i = 1; i < (sd / 2); i++) {
  44102. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  44103. this._storeIndex(ib, ibi, i * 3 + 0, c);
  44104. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  44105. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  44106. curA += incA;
  44107. }
  44108. }
  44109. break;
  44110. }
  44111. case Lines2D.SquareAnchorCap:
  44112. {
  44113. var vi = 0;
  44114. var c = borderMode ? null : contour;
  44115. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  44116. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  44117. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  44118. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  44119. if (borderMode) {
  44120. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  44121. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  44122. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  44123. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  44124. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  44125. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  44126. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  44127. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  44128. var ii = 0;
  44129. this._storeIndex(ib, ibi, ii++, v6);
  44130. this._storeIndex(ib, ibi, ii++, v1);
  44131. this._storeIndex(ib, ibi, ii++, v5);
  44132. this._storeIndex(ib, ibi, ii++, v6);
  44133. this._storeIndex(ib, ibi, ii++, v7);
  44134. this._storeIndex(ib, ibi, ii++, v1);
  44135. this._storeIndex(ib, ibi, ii++, v1);
  44136. this._storeIndex(ib, ibi, ii++, v7);
  44137. this._storeIndex(ib, ibi, ii++, v8);
  44138. this._storeIndex(ib, ibi, ii++, v1);
  44139. this._storeIndex(ib, ibi, ii++, v8);
  44140. this._storeIndex(ib, ibi, ii++, v2);
  44141. this._storeIndex(ib, ibi, ii++, v2);
  44142. this._storeIndex(ib, ibi, ii++, v8);
  44143. this._storeIndex(ib, ibi, ii++, v9);
  44144. this._storeIndex(ib, ibi, ii++, v2);
  44145. this._storeIndex(ib, ibi, ii++, v9);
  44146. this._storeIndex(ib, ibi, ii++, v3);
  44147. this._storeIndex(ib, ibi, ii++, v3);
  44148. this._storeIndex(ib, ibi, ii++, v9);
  44149. this._storeIndex(ib, ibi, ii++, v10);
  44150. this._storeIndex(ib, ibi, ii++, v3);
  44151. this._storeIndex(ib, ibi, ii++, v10);
  44152. this._storeIndex(ib, ibi, ii++, v4);
  44153. this._storeIndex(ib, ibi, ii++, v10);
  44154. this._storeIndex(ib, ibi, ii++, v11);
  44155. this._storeIndex(ib, ibi, ii++, v4);
  44156. this._storeIndex(ib, ibi, ii++, v11);
  44157. this._storeIndex(ib, ibi, ii++, v12);
  44158. this._storeIndex(ib, ibi, ii++, v4);
  44159. }
  44160. else {
  44161. this._storeIndex(ib, ibi, 0, v1);
  44162. this._storeIndex(ib, ibi, 1, v2);
  44163. this._storeIndex(ib, ibi, 2, v3);
  44164. this._storeIndex(ib, ibi, 3, v1);
  44165. this._storeIndex(ib, ibi, 4, v3);
  44166. this._storeIndex(ib, ibi, 5, v4);
  44167. }
  44168. break;
  44169. }
  44170. case Lines2D.RoundAnchorCap:
  44171. {
  44172. var cpos = Math.sqrt(t * t - ht * ht);
  44173. var center = new BABYLON.Vector2(cpos, 0);
  44174. var curA = BABYLON.Tools.ToRadians(-150);
  44175. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  44176. if (borderMode) {
  44177. var ii = 0;
  44178. for (var i = 0; i < sd; i++) {
  44179. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  44180. 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);
  44181. if (i > 0) {
  44182. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44183. this._storeIndex(ib, ibi, ii++, v2 - 2);
  44184. this._storeIndex(ib, ibi, ii++, v2);
  44185. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44186. this._storeIndex(ib, ibi, ii++, v2);
  44187. this._storeIndex(ib, ibi, ii++, v1);
  44188. }
  44189. curA += incA;
  44190. }
  44191. }
  44192. else {
  44193. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  44194. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  44195. curA += incA;
  44196. for (var i = 1; i < sd; i++) {
  44197. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  44198. this._storeIndex(ib, ibi, i * 3 + 0, c);
  44199. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  44200. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  44201. curA += incA;
  44202. }
  44203. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  44204. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  44205. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  44206. }
  44207. break;
  44208. }
  44209. case Lines2D.DiamondAnchorCap:
  44210. {
  44211. var vi = 0;
  44212. var c = borderMode ? null : contour;
  44213. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  44214. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  44215. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  44216. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  44217. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  44218. if (borderMode) {
  44219. var f = Math.sqrt(bt * bt * 2);
  44220. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  44221. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  44222. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  44223. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  44224. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  44225. var ii = 0;
  44226. this._storeIndex(ib, ibi, ii++, v6);
  44227. this._storeIndex(ib, ibi, ii++, v7);
  44228. this._storeIndex(ib, ibi, ii++, v1);
  44229. this._storeIndex(ib, ibi, ii++, v1);
  44230. this._storeIndex(ib, ibi, ii++, v7);
  44231. this._storeIndex(ib, ibi, ii++, v2);
  44232. this._storeIndex(ib, ibi, ii++, v2);
  44233. this._storeIndex(ib, ibi, ii++, v7);
  44234. this._storeIndex(ib, ibi, ii++, v8);
  44235. this._storeIndex(ib, ibi, ii++, v2);
  44236. this._storeIndex(ib, ibi, ii++, v8);
  44237. this._storeIndex(ib, ibi, ii++, v3);
  44238. this._storeIndex(ib, ibi, ii++, v3);
  44239. this._storeIndex(ib, ibi, ii++, v8);
  44240. this._storeIndex(ib, ibi, ii++, v9);
  44241. this._storeIndex(ib, ibi, ii++, v3);
  44242. this._storeIndex(ib, ibi, ii++, v9);
  44243. this._storeIndex(ib, ibi, ii++, v4);
  44244. this._storeIndex(ib, ibi, ii++, v4);
  44245. this._storeIndex(ib, ibi, ii++, v9);
  44246. this._storeIndex(ib, ibi, ii++, v10);
  44247. this._storeIndex(ib, ibi, ii++, v4);
  44248. this._storeIndex(ib, ibi, ii++, v10);
  44249. this._storeIndex(ib, ibi, ii++, v5);
  44250. }
  44251. else {
  44252. this._storeIndex(ib, ibi, 0, v1);
  44253. this._storeIndex(ib, ibi, 1, v2);
  44254. this._storeIndex(ib, ibi, 2, v3);
  44255. this._storeIndex(ib, ibi, 3, v1);
  44256. this._storeIndex(ib, ibi, 4, v3);
  44257. this._storeIndex(ib, ibi, 5, v5);
  44258. this._storeIndex(ib, ibi, 6, v5);
  44259. this._storeIndex(ib, ibi, 7, v3);
  44260. this._storeIndex(ib, ibi, 8, v4);
  44261. }
  44262. break;
  44263. }
  44264. }
  44265. return null;
  44266. };
  44267. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  44268. var lineA = BABYLON.Vector2.Zero();
  44269. var lineB = BABYLON.Vector2.Zero();
  44270. var tangent = BABYLON.Vector2.Zero();
  44271. var miter = BABYLON.Vector2.Zero();
  44272. var curNormal = null;
  44273. if (this.closed) {
  44274. this.points.push(this.points[0]);
  44275. }
  44276. var total = this.points.length;
  44277. for (var i = 1; i < total; i++) {
  44278. var last = this.points[i - 1];
  44279. var cur = this.points[i];
  44280. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  44281. this._direction(cur, last, lineA);
  44282. if (!curNormal) {
  44283. curNormal = BABYLON.Vector2.Zero();
  44284. this._perp(lineA, curNormal);
  44285. }
  44286. if (i === 1) {
  44287. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  44288. }
  44289. if (!next) {
  44290. this._perp(lineA, curNormal);
  44291. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  44292. }
  44293. else {
  44294. this._direction(next, cur, lineB);
  44295. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  44296. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  44297. }
  44298. }
  44299. if (this.points.length > 2 && this.closed) {
  44300. var last2 = this.points[total - 2];
  44301. var cur2 = this.points[0];
  44302. var next2 = this.points[1];
  44303. this._direction(cur2, last2, lineA);
  44304. this._direction(next2, cur2, lineB);
  44305. this._perp(lineA, curNormal);
  44306. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  44307. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  44308. // Patch contour
  44309. if (contour) {
  44310. var off = (bt == null) ? 0 : 4;
  44311. contour[0].x = vb[off + 0];
  44312. contour[0].y = vb[off + 1];
  44313. contour[1].x = vb[off + 2];
  44314. contour[1].y = vb[off + 3];
  44315. }
  44316. }
  44317. // Remove the point we added at the beginning
  44318. if (this.closed) {
  44319. this.points.splice(total - 1);
  44320. }
  44321. };
  44322. // Methods for Lines building
  44323. ///////////////////////////////////////////////////////////////////////////////////
  44324. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44325. var renderCache = modelRenderCache;
  44326. var engine = this.owner.engine;
  44327. if (this._fillVB === null) {
  44328. this._computeLines2D();
  44329. }
  44330. // Need to create WebGL resources for fill part?
  44331. if (this.fill) {
  44332. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  44333. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  44334. renderCache.fillIndicesCount = this._fillIB.length;
  44335. // 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
  44336. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  44337. if (ei) {
  44338. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44339. }
  44340. // Get the non instanced version
  44341. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  44342. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44343. }
  44344. // Need to create WebGL resources for border part?
  44345. if (this.border) {
  44346. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  44347. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  44348. renderCache.borderIndicesCount = this._borderIB.length;
  44349. // 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
  44350. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  44351. if (ei) {
  44352. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44353. }
  44354. // Get the non instanced version
  44355. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  44356. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44357. }
  44358. this._fillVB = null;
  44359. this._fillIB = null;
  44360. this._borderVB = null;
  44361. this._borderIB = null;
  44362. return renderCache;
  44363. };
  44364. Lines2D.prototype._computeLines2D = function () {
  44365. // Init min/max because their being computed here
  44366. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  44367. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  44368. var contour = new Array();
  44369. var startCapContour = new Array();
  44370. var endCapContour = new Array();
  44371. // Need to create WebGL resources for fill part?
  44372. if (this.fill) {
  44373. var startCapInfo = this._getCapSize(this.startCap);
  44374. var endCapInfo = this._getCapSize(this.endCap);
  44375. var count = this.points.length;
  44376. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  44377. this._fillVB = new Float32Array(vbSize);
  44378. var vb = this._fillVB;
  44379. var ht = this.fillThickness / 2;
  44380. var total = this.points.length;
  44381. this._buildLine(vb, this.border ? null : contour, ht);
  44382. var max = total * 2;
  44383. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  44384. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  44385. var ib = this._fillIB;
  44386. for (var i = 0; i < triCount; i += 2) {
  44387. ib[i * 3 + 0] = i + 0;
  44388. ib[i * 3 + 1] = i + 1;
  44389. ib[i * 3 + 2] = (i + 2) % max;
  44390. ib[i * 3 + 3] = i + 1;
  44391. ib[i * 3 + 4] = (i + 3) % max;
  44392. ib[i * 3 + 5] = (i + 2) % max;
  44393. }
  44394. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  44395. 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);
  44396. }
  44397. // Need to create WebGL resources for border part?
  44398. if (this.border) {
  44399. var startCapInfo = this._getCapSize(this.startCap, true);
  44400. var endCapInfo = this._getCapSize(this.endCap, true);
  44401. var count = this.points.length;
  44402. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  44403. this._borderVB = new Float32Array(vbSize);
  44404. var vb = this._borderVB;
  44405. var ht = this.fillThickness / 2;
  44406. var bt = this.borderThickness;
  44407. var total = this.points.length;
  44408. this._buildLine(vb, contour, ht, bt);
  44409. var max = total * 2 * 2;
  44410. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  44411. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  44412. var ib = this._borderIB;
  44413. for (var i = 0; i < triCount; i += 4) {
  44414. ib[i * 3 + 0] = i + 0;
  44415. ib[i * 3 + 1] = i + 2;
  44416. ib[i * 3 + 2] = (i + 6) % max;
  44417. ib[i * 3 + 3] = i + 0;
  44418. ib[i * 3 + 4] = (i + 6) % max;
  44419. ib[i * 3 + 5] = (i + 4) % max;
  44420. ib[i * 3 + 6] = i + 3;
  44421. ib[i * 3 + 7] = i + 1;
  44422. ib[i * 3 + 8] = (i + 5) % max;
  44423. ib[i * 3 + 9] = i + 3;
  44424. ib[i * 3 + 10] = (i + 5) % max;
  44425. ib[i * 3 + 11] = (i + 7) % max;
  44426. }
  44427. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  44428. 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);
  44429. }
  44430. this._contour = contour;
  44431. if (startCapContour.length > 0) {
  44432. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  44433. this._startCapTriIndices = startCapTri;
  44434. this._startCapContour = startCapContour;
  44435. }
  44436. if (endCapContour.length > 0) {
  44437. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  44438. this._endCapContour = endCapContour;
  44439. this._endCapTriIndices = endCapTri;
  44440. }
  44441. var bs = this._boundingMax.subtract(this._boundingMin);
  44442. this._size.width = bs.x;
  44443. this._size.height = bs.y;
  44444. };
  44445. Object.defineProperty(Lines2D.prototype, "size", {
  44446. get: function () {
  44447. if (this._size == null) {
  44448. this._computeLines2D();
  44449. }
  44450. return this._size;
  44451. },
  44452. enumerable: true,
  44453. configurable: true
  44454. });
  44455. Lines2D.prototype.createInstanceDataParts = function () {
  44456. var res = new Array();
  44457. if (this.border) {
  44458. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44459. }
  44460. if (this.fill) {
  44461. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44462. }
  44463. return res;
  44464. };
  44465. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  44466. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44467. return false;
  44468. }
  44469. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44470. var d = part;
  44471. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  44472. d.boundingMin = this.boundingMin;
  44473. d.boundingMax = this.boundingMax;
  44474. }
  44475. }
  44476. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44477. var d = part;
  44478. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  44479. d.boundingMin = this.boundingMin;
  44480. d.boundingMax = this.boundingMax;
  44481. }
  44482. }
  44483. return true;
  44484. };
  44485. Lines2D._prevA = BABYLON.Vector2.Zero();
  44486. Lines2D._prevB = BABYLON.Vector2.Zero();
  44487. Lines2D._curA = BABYLON.Vector2.Zero();
  44488. Lines2D._curB = BABYLON.Vector2.Zero();
  44489. Lines2D._miterTps = BABYLON.Vector2.Zero();
  44490. Lines2D._startDir = BABYLON.Vector2.Zero();
  44491. Lines2D._endDir = BABYLON.Vector2.Zero();
  44492. Lines2D._tpsV = BABYLON.Vector2.Zero();
  44493. Lines2D._noCap = 0;
  44494. Lines2D._roundCap = 1;
  44495. Lines2D._triangleCap = 2;
  44496. Lines2D._squareAnchorCap = 3;
  44497. Lines2D._roundAnchorCap = 4;
  44498. Lines2D._diamondAnchorCap = 5;
  44499. Lines2D._arrowCap = 6;
  44500. Lines2D._roundCapSubDiv = 36;
  44501. __decorate([
  44502. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  44503. ], Lines2D.prototype, "points", null);
  44504. __decorate([
  44505. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  44506. ], Lines2D.prototype, "fillThickness", null);
  44507. __decorate([
  44508. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  44509. ], Lines2D.prototype, "closed", null);
  44510. __decorate([
  44511. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  44512. ], Lines2D.prototype, "startCap", null);
  44513. __decorate([
  44514. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  44515. ], Lines2D.prototype, "endCap", null);
  44516. Lines2D = __decorate([
  44517. BABYLON.className("Lines2D")
  44518. ], Lines2D);
  44519. return Lines2D;
  44520. })(BABYLON.Shape2D);
  44521. BABYLON.Lines2D = Lines2D;
  44522. })(BABYLON || (BABYLON = {}));
  44523. var BABYLON;
  44524. (function (BABYLON) {
  44525. // This class contains data that lifetime is bounding to the Babylon Engine object
  44526. var Canvas2DEngineBoundData = (function () {
  44527. function Canvas2DEngineBoundData() {
  44528. this._modelCache = new BABYLON.StringDictionary();
  44529. }
  44530. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  44531. return this._modelCache.getOrAddWithFactory(key, factory);
  44532. };
  44533. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  44534. if (!modelRenderCache.isDisposed) {
  44535. return false;
  44536. }
  44537. this._modelCache.remove(modelRenderCache.modelKey);
  44538. return true;
  44539. };
  44540. return Canvas2DEngineBoundData;
  44541. })();
  44542. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  44543. var Canvas2D = (function (_super) {
  44544. __extends(Canvas2D, _super);
  44545. function Canvas2D(scene, settings) {
  44546. var _this = this;
  44547. _super.call(this, settings);
  44548. /**
  44549. * 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.
  44550. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  44551. */
  44552. this.worldSpaceToNodeLocal = function (worldPos) {
  44553. var node = _this._worldSpaceNode;
  44554. if (!node) {
  44555. return;
  44556. }
  44557. var mtx = node.getWorldMatrix().clone();
  44558. mtx.invert();
  44559. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  44560. var res = new BABYLON.Vector2(v.x, v.y);
  44561. var size = _this.actualSize;
  44562. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  44563. res.y += size.width * 0.5;
  44564. return res;
  44565. };
  44566. /**
  44567. * 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
  44568. */
  44569. this.worldSpaceCacheChanged = function () {
  44570. var plane = _this.worldSpaceCanvasNode;
  44571. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  44572. vd.uvs = new Float32Array(8);
  44573. var material = plane.material;
  44574. var tex = _this._renderableData._cacheTexture;
  44575. if (material.diffuseTexture !== tex) {
  44576. material.diffuseTexture = tex;
  44577. tex.hasAlpha = true;
  44578. }
  44579. var nodeuv = _this._renderableData._cacheNodeUVs;
  44580. for (var i = 0; i < 4; i++) {
  44581. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  44582. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  44583. }
  44584. vd.applyToMesh(plane);
  44585. };
  44586. this._notifDebugMode = false;
  44587. this._mapCounter = 0;
  44588. BABYLON.Prim2DBase._isCanvasInit = false;
  44589. if (!settings) {
  44590. settings = {};
  44591. }
  44592. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44593. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  44594. this._background.zOrder = 1.0;
  44595. this._background.isPickable = false;
  44596. this._background.origin = BABYLON.Vector2.Zero();
  44597. this._background.levelVisible = false;
  44598. if (settings.backgroundRoundRadius != null) {
  44599. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  44600. }
  44601. if (settings.backgroundBorder != null) {
  44602. if (typeof (settings.backgroundBorder) === "string") {
  44603. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  44604. }
  44605. else {
  44606. this.backgroundBorder = settings.backgroundBorder;
  44607. }
  44608. }
  44609. if (settings.backgroundBorderThickNess != null) {
  44610. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  44611. }
  44612. if (settings.backgroundFill != null) {
  44613. if (typeof (settings.backgroundFill) === "string") {
  44614. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  44615. }
  44616. else {
  44617. this.backgroundFill = settings.backgroundFill;
  44618. }
  44619. }
  44620. this._background._patchHierarchy(this);
  44621. }
  44622. var engine = scene.getEngine();
  44623. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  44624. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  44625. this._capturedPointers = new BABYLON.StringDictionary();
  44626. this._pickStartingPosition = BABYLON.Vector2.Zero();
  44627. this._hierarchyLevelMaxSiblingCount = 50;
  44628. this._hierarchyDepthOffset = 0;
  44629. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  44630. this._scene = scene;
  44631. this._engine = engine;
  44632. this._renderingSize = new BABYLON.Size(0, 0);
  44633. this._trackedGroups = new Array();
  44634. this._maxAdaptiveWorldSpaceCanvasSize = null;
  44635. this._groupCacheMaps = new BABYLON.StringDictionary();
  44636. this._patchHierarchy(this);
  44637. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  44638. this._fitRenderingDevice = !settings.size;
  44639. if (!settings.size) {
  44640. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  44641. }
  44642. // Register scene dispose to also dispose the canvas when it'll happens
  44643. scene.onDisposeObservable.add(function (d, s) {
  44644. _this.dispose();
  44645. });
  44646. if (this._isScreenSpace) {
  44647. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  44648. _this._engine.clear(null, false, true);
  44649. _this._render();
  44650. });
  44651. }
  44652. else {
  44653. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  44654. _this._render();
  44655. });
  44656. }
  44657. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  44658. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  44659. this._setupInteraction(enableInteraction);
  44660. }
  44661. Canvas2D.prototype._canvasPreInit = function (settings) {
  44662. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  44663. this._cachingStrategy = cachingStrategy;
  44664. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  44665. };
  44666. Canvas2D.prototype._setupInteraction = function (enable) {
  44667. var _this = this;
  44668. // No change detection
  44669. if (enable === this._interactionEnabled) {
  44670. return;
  44671. }
  44672. // Set the new state
  44673. this._interactionEnabled = enable;
  44674. // ScreenSpace mode
  44675. if (this._isScreenSpace) {
  44676. // Disable interaction
  44677. if (!enable) {
  44678. if (this._scenePrePointerObserver) {
  44679. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  44680. this._scenePrePointerObserver = null;
  44681. }
  44682. return;
  44683. }
  44684. // Enable Interaction
  44685. // Register the observable
  44686. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  44687. var hs = 1 / _this.engine.getHardwareScalingLevel();
  44688. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  44689. _this._handlePointerEventForInteraction(e, localPos, s);
  44690. });
  44691. }
  44692. else {
  44693. var scene = this.scene;
  44694. if (enable) {
  44695. scene.constantlyUpdateMeshUnderPointer = true;
  44696. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  44697. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  44698. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  44699. _this._handlePointerEventForInteraction(e, localPos, s);
  44700. }
  44701. });
  44702. }
  44703. else {
  44704. if (this._scenePointerObserver) {
  44705. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  44706. this._scenePointerObserver = null;
  44707. }
  44708. }
  44709. }
  44710. };
  44711. /**
  44712. * Internal method, you should use the Prim2DBase version instead
  44713. */
  44714. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  44715. if (this.isPointerCaptured(pointerId)) {
  44716. return false;
  44717. }
  44718. // Try to capture the pointer on the HTML side
  44719. try {
  44720. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  44721. }
  44722. catch (e) {
  44723. }
  44724. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  44725. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  44726. this._capturedPointers.add(pointerId.toString(), primitive);
  44727. return true;
  44728. };
  44729. /**
  44730. * Internal method, you should use the Prim2DBase version instead
  44731. */
  44732. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  44733. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  44734. return false;
  44735. }
  44736. // Try to release the pointer on the HTML side
  44737. try {
  44738. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  44739. }
  44740. catch (e) {
  44741. }
  44742. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  44743. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  44744. this._capturedPointers.remove(pointerId.toString());
  44745. return true;
  44746. };
  44747. /**
  44748. * Determine if the given pointer is captured or not
  44749. * @param pointerId the Id of the pointer
  44750. * @return true if it's captured, false otherwise
  44751. */
  44752. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  44753. return this._capturedPointers.contains(pointerId.toString());
  44754. };
  44755. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  44756. // Avoid unnecessary lookup
  44757. if (this._capturedPointers.count === 0) {
  44758. return null;
  44759. }
  44760. return this._capturedPointers.get(pointerId.toString());
  44761. };
  44762. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  44763. // Dispose check
  44764. if (this.isDisposed) {
  44765. return;
  44766. }
  44767. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  44768. this._updatePointerInfo(eventData, localPosition);
  44769. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  44770. // 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.
  44771. // 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.
  44772. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  44773. // 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
  44774. this._updateOverStatus();
  44775. // Check if we have nothing to raise
  44776. if (!this._actualOverPrimitive && !capturedPrim) {
  44777. return;
  44778. }
  44779. // Update the relatedTarget info with the over primitive or the captured one (if any)
  44780. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  44781. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  44782. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  44783. // Analyze the pointer event type and fire proper events on the primitive
  44784. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  44785. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  44786. }
  44787. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44788. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  44789. }
  44790. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44791. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  44792. }
  44793. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  44794. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  44795. }
  44796. };
  44797. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  44798. var pii = this._primPointerInfo;
  44799. if (!pii.canvasPointerPos) {
  44800. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  44801. }
  44802. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  44803. var engine = this._scene.getEngine();
  44804. if (this._isScreenSpace) {
  44805. var cameraViewport = camera.viewport;
  44806. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  44807. // Moving coordinates to local viewport world
  44808. var x = localPosition.x - viewport.x;
  44809. var y = localPosition.y - viewport.y;
  44810. pii.canvasPointerPos.x = x - this.actualPosition.x;
  44811. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  44812. }
  44813. else {
  44814. pii.canvasPointerPos.x = localPosition.x;
  44815. pii.canvasPointerPos.y = localPosition.y;
  44816. }
  44817. pii.mouseWheelDelta = 0;
  44818. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  44819. var event = eventData.event;
  44820. if (event.wheelDelta) {
  44821. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  44822. }
  44823. else if (event.detail) {
  44824. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  44825. }
  44826. }
  44827. else {
  44828. var pe = eventData.event;
  44829. pii.ctrlKey = pe.ctrlKey;
  44830. pii.altKey = pe.altKey;
  44831. pii.shiftKey = pe.shiftKey;
  44832. pii.metaKey = pe.metaKey;
  44833. pii.button = pe.button;
  44834. pii.buttons = pe.buttons;
  44835. pii.pointerId = pe.pointerId;
  44836. pii.width = pe.width;
  44837. pii.height = pe.height;
  44838. pii.presssure = pe.pressure;
  44839. pii.tilt.x = pe.tiltX;
  44840. pii.tilt.y = pe.tiltY;
  44841. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  44842. }
  44843. };
  44844. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  44845. if (this.scene.getRenderId() === this._intersectionRenderId) {
  44846. return;
  44847. }
  44848. // 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
  44849. if (!this._globalTransform) {
  44850. this.updateCachedStates(true);
  44851. }
  44852. var ii = Canvas2D._interInfo;
  44853. ii.pickPosition.x = mouseLocalPos.x;
  44854. ii.pickPosition.y = mouseLocalPos.y;
  44855. ii.findFirstOnly = false;
  44856. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  44857. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  44858. this._previousIntersectionList = this._actualIntersectionList;
  44859. this._actualIntersectionList = null;
  44860. this._previousOverPrimitive = this._actualOverPrimitive;
  44861. this._actualOverPrimitive = null;
  44862. return;
  44863. }
  44864. this.intersect(ii);
  44865. this._previousIntersectionList = this._actualIntersectionList;
  44866. this._actualIntersectionList = ii.intersectedPrimitives;
  44867. this._previousOverPrimitive = this._actualOverPrimitive;
  44868. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  44869. this._intersectionRenderId = this.scene.getRenderId();
  44870. };
  44871. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  44872. Canvas2D.prototype._updateOverStatus = function () {
  44873. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  44874. return;
  44875. }
  44876. // Detect a change of over
  44877. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  44878. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  44879. if (prevPrim !== actualPrim) {
  44880. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  44881. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  44882. // Notify the previous "over" prim that the pointer is no longer over it
  44883. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  44884. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  44885. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  44886. }
  44887. // Notify the new "over" prim that the pointer is over it
  44888. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  44889. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  44890. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  44891. }
  44892. }
  44893. this._hoverStatusRenderId = this.scene.getRenderId();
  44894. };
  44895. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  44896. if (this._primPointerInfo.isCaptured) {
  44897. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  44898. }
  44899. else {
  44900. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  44901. var pii = _a[_i];
  44902. if (pii.prim === prim) {
  44903. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  44904. return;
  44905. }
  44906. }
  44907. }
  44908. };
  44909. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  44910. if (!this._notifDebugMode) {
  44911. return;
  44912. }
  44913. var debug = "";
  44914. for (var i = 0; i < prim.hierarchyDepth; i++) {
  44915. debug += " ";
  44916. }
  44917. var pii = this._primPointerInfo;
  44918. 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();
  44919. console.log(debug);
  44920. };
  44921. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  44922. var ppi = this._primPointerInfo;
  44923. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  44924. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  44925. this._notifParents(prim, mask);
  44926. }
  44927. var bubbleCancelled = false;
  44928. var cur = prim;
  44929. while (cur) {
  44930. // Only trigger the observers if the primitive is intersected (except for out)
  44931. if (!bubbleCancelled) {
  44932. this._updatePrimPointerPos(cur);
  44933. // Exec the observers
  44934. this._debugExecObserver(cur, mask);
  44935. cur._pointerEventObservable.notifyObservers(ppi, mask);
  44936. this._triggerActionManager(cur, ppi, mask, eventData);
  44937. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  44938. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  44939. if (ppi.cancelBubble) {
  44940. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  44941. return;
  44942. }
  44943. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  44944. bubbleCancelled = true;
  44945. }
  44946. }
  44947. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  44948. if (bubbleCancelled) {
  44949. this._updatePrimPointerPos(cur);
  44950. }
  44951. // Trigger a PointerEnter corresponding to the PointerOver
  44952. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  44953. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  44954. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  44955. }
  44956. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  44957. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  44958. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  44959. }
  44960. // Loop to the parent
  44961. cur = cur.parent;
  44962. }
  44963. };
  44964. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  44965. var _this = this;
  44966. // 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
  44967. if (!this._globalTransform) {
  44968. this.updateCachedStates(true);
  44969. }
  44970. // Process Trigger related to PointerDown
  44971. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  44972. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  44973. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  44974. this._pickStartingTime = new Date().getTime();
  44975. this._pickedDownPrim = null;
  44976. if (prim.actionManager) {
  44977. this._pickedDownPrim = prim;
  44978. if (prim.actionManager.hasPickTriggers) {
  44979. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  44980. switch (eventData.button) {
  44981. case 0:
  44982. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  44983. break;
  44984. case 1:
  44985. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  44986. break;
  44987. case 2:
  44988. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  44989. break;
  44990. }
  44991. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  44992. }
  44993. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  44994. window.setTimeout(function () {
  44995. var ppi = _this._primPointerInfo;
  44996. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  44997. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  44998. var ii = new BABYLON.IntersectInfo2D();
  44999. ii.pickPosition = ppi.canvasPointerPos.clone();
  45000. ii.findFirstOnly = false;
  45001. _this.intersect(ii);
  45002. if (ii.isPrimIntersected(prim) !== null) {
  45003. if (prim.actionManager) {
  45004. 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)) {
  45005. _this._pickStartingTime = 0;
  45006. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  45007. }
  45008. }
  45009. }
  45010. }, BABYLON.ActionManager.LongPressDelay);
  45011. }
  45012. }
  45013. }
  45014. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  45015. this._pickStartingTime = 0;
  45016. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45017. if (prim.actionManager) {
  45018. // OnPickUpTrigger
  45019. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  45020. // OnPickTrigger
  45021. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  45022. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  45023. }
  45024. }
  45025. // OnPickOutTrigger
  45026. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  45027. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  45028. }
  45029. }
  45030. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  45031. if (prim.actionManager) {
  45032. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45033. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  45034. }
  45035. }
  45036. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  45037. if (prim.actionManager) {
  45038. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45039. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  45040. }
  45041. }
  45042. };
  45043. Canvas2D.prototype._notifParents = function (prim, mask) {
  45044. var pii = this._primPointerInfo;
  45045. var curPrim = this;
  45046. while (curPrim) {
  45047. this._updatePrimPointerPos(curPrim);
  45048. // Fire the proper notification
  45049. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45050. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  45051. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  45052. }
  45053. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45054. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  45055. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  45056. }
  45057. curPrim = curPrim.parent;
  45058. }
  45059. };
  45060. /**
  45061. * Don't forget to call the dispose method when you're done with the Canvas instance.
  45062. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  45063. */
  45064. Canvas2D.prototype.dispose = function () {
  45065. if (!_super.prototype.dispose.call(this)) {
  45066. return false;
  45067. }
  45068. if (this.interactionEnabled) {
  45069. this._setupInteraction(false);
  45070. }
  45071. if (this._beforeRenderObserver) {
  45072. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  45073. this._beforeRenderObserver = null;
  45074. }
  45075. if (this._afterRenderObserver) {
  45076. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  45077. this._afterRenderObserver = null;
  45078. }
  45079. if (this._groupCacheMaps) {
  45080. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  45081. this._groupCacheMaps = null;
  45082. }
  45083. };
  45084. Object.defineProperty(Canvas2D.prototype, "scene", {
  45085. /**
  45086. * Accessor to the Scene that owns the Canvas
  45087. * @returns The instance of the Scene object
  45088. */
  45089. get: function () {
  45090. return this._scene;
  45091. },
  45092. enumerable: true,
  45093. configurable: true
  45094. });
  45095. Object.defineProperty(Canvas2D.prototype, "engine", {
  45096. /**
  45097. * Accessor to the Engine that drives the Scene used by this Canvas
  45098. * @returns The instance of the Engine object
  45099. */
  45100. get: function () {
  45101. return this._engine;
  45102. },
  45103. enumerable: true,
  45104. configurable: true
  45105. });
  45106. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  45107. /**
  45108. * Accessor of the Caching Strategy used by this Canvas.
  45109. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  45110. * @returns the value corresponding to the used strategy.
  45111. */
  45112. get: function () {
  45113. return this._cachingStrategy;
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  45119. /**
  45120. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  45121. * @returns {}
  45122. */
  45123. get: function () {
  45124. return this._isScreenSpace;
  45125. },
  45126. enumerable: true,
  45127. configurable: true
  45128. });
  45129. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  45130. /**
  45131. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  45132. */
  45133. get: function () {
  45134. return this._worldSpaceNode;
  45135. },
  45136. set: function (val) {
  45137. this._worldSpaceNode = val;
  45138. },
  45139. enumerable: true,
  45140. configurable: true
  45141. });
  45142. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  45143. /**
  45144. * Check if the WebGL Instanced Array extension is supported or not
  45145. */
  45146. get: function () {
  45147. return this._supprtInstancedArray;
  45148. },
  45149. enumerable: true,
  45150. configurable: true
  45151. });
  45152. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  45153. /**
  45154. * Property that defines the fill object used to draw the background of the Canvas.
  45155. * Note that Canvas with a Caching Strategy of
  45156. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  45157. */
  45158. get: function () {
  45159. if (!this._background || !this._background.isVisible) {
  45160. return null;
  45161. }
  45162. return this._background.fill;
  45163. },
  45164. set: function (value) {
  45165. this.checkBackgroundAvailability();
  45166. if (value === this._background.fill) {
  45167. return;
  45168. }
  45169. this._background.fill = value;
  45170. this._background.levelVisible = true;
  45171. },
  45172. enumerable: true,
  45173. configurable: true
  45174. });
  45175. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  45176. /**
  45177. * Property that defines the border object used to draw the background of the Canvas.
  45178. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  45179. */
  45180. get: function () {
  45181. if (!this._background || !this._background.isVisible) {
  45182. return null;
  45183. }
  45184. return this._background.border;
  45185. },
  45186. set: function (value) {
  45187. this.checkBackgroundAvailability();
  45188. if (value === this._background.border) {
  45189. return;
  45190. }
  45191. this._background.border = value;
  45192. this._background.levelVisible = true;
  45193. },
  45194. enumerable: true,
  45195. configurable: true
  45196. });
  45197. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  45198. /**
  45199. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  45200. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  45201. */
  45202. get: function () {
  45203. if (!this._background || !this._background.isVisible) {
  45204. return null;
  45205. }
  45206. return this._background.borderThickness;
  45207. },
  45208. set: function (value) {
  45209. this.checkBackgroundAvailability();
  45210. if (value === this._background.borderThickness) {
  45211. return;
  45212. }
  45213. this._background.borderThickness = value;
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  45219. /**
  45220. * You can set the roundRadius of the background
  45221. * @returns The current roundRadius
  45222. */
  45223. get: function () {
  45224. if (!this._background || !this._background.isVisible) {
  45225. return null;
  45226. }
  45227. return this._background.roundRadius;
  45228. },
  45229. set: function (value) {
  45230. this.checkBackgroundAvailability();
  45231. if (value === this._background.roundRadius) {
  45232. return;
  45233. }
  45234. this._background.roundRadius = value;
  45235. this._background.levelVisible = true;
  45236. },
  45237. enumerable: true,
  45238. configurable: true
  45239. });
  45240. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  45241. /**
  45242. * Enable/Disable interaction for this Canvas
  45243. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  45244. */
  45245. get: function () {
  45246. return this._interactionEnabled;
  45247. },
  45248. set: function (enable) {
  45249. this._setupInteraction(enable);
  45250. },
  45251. enumerable: true,
  45252. configurable: true
  45253. });
  45254. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  45255. /**
  45256. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  45257. * @returns {}
  45258. */
  45259. get: function () {
  45260. return this.__engineData;
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. Canvas2D.prototype.checkBackgroundAvailability = function () {
  45266. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  45267. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  45268. }
  45269. };
  45270. Canvas2D.prototype.onPrimBecomesDirty = function () {
  45271. this._addPrimToDirtyList(this);
  45272. };
  45273. Canvas2D.prototype._updateTrackedNodes = function () {
  45274. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  45275. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  45276. var rh = this.engine.getRenderHeight();
  45277. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  45278. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  45279. var group = _a[_i];
  45280. if (group.isDisposed || !group.isVisible) {
  45281. continue;
  45282. }
  45283. var node = group.trackedNode;
  45284. var worldMtx = node.getWorldMatrix();
  45285. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  45286. group.x = Math.round(proj.x);
  45287. group.y = Math.round(rh - proj.y);
  45288. }
  45289. };
  45290. /**
  45291. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  45292. */
  45293. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  45294. this._updateCanvasState(forceRecompute);
  45295. };
  45296. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  45297. if (this._globalTransformStep < 2) {
  45298. return;
  45299. }
  45300. var n = this.worldSpaceCanvasNode;
  45301. var bi = n.getBoundingInfo().boundingBox;
  45302. var v = bi.vectorsWorld;
  45303. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  45304. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  45305. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  45306. var projPoints = new Array(4);
  45307. for (var i = 0; i < 4; i++) {
  45308. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  45309. }
  45310. var left = projPoints[3].subtract(projPoints[0]).length();
  45311. var top = projPoints[3].subtract(projPoints[1]).length();
  45312. var right = projPoints[1].subtract(projPoints[2]).length();
  45313. var bottom = projPoints[2].subtract(projPoints[0]).length();
  45314. var w = Math.round(Math.max(top, bottom));
  45315. var h = Math.round(Math.max(right, left));
  45316. var isW = w > h;
  45317. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  45318. var edge = Math.max(w, h);
  45319. if (edge < 256) {
  45320. edge = 256;
  45321. }
  45322. else {
  45323. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  45324. }
  45325. // Clip values if needed
  45326. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  45327. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  45328. if (newScale !== this.scale) {
  45329. var scale = newScale;
  45330. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  45331. this._setRenderingScale(scale);
  45332. }
  45333. };
  45334. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  45335. // Check if the update has already been made for this render Frame
  45336. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  45337. return;
  45338. }
  45339. // Detect a change of rendering size
  45340. var renderingSizeChanged = false;
  45341. var newWidth = this.engine.getRenderWidth();
  45342. if (newWidth !== this._renderingSize.width) {
  45343. renderingSizeChanged = true;
  45344. }
  45345. this._renderingSize.width = newWidth;
  45346. var newHeight = this.engine.getRenderHeight();
  45347. if (newHeight !== this._renderingSize.height) {
  45348. renderingSizeChanged = true;
  45349. }
  45350. this._renderingSize.height = newHeight;
  45351. // If the canvas fit the rendering size and it changed, update
  45352. if (renderingSizeChanged && this._fitRenderingDevice) {
  45353. this.size = this._renderingSize;
  45354. if (this._background) {
  45355. this._background.size = this.size;
  45356. }
  45357. // Dirty the Layout at the Canvas level to recompute as the size changed
  45358. this._setLayoutDirty();
  45359. }
  45360. var context = new BABYLON.PrepareRender2DContext();
  45361. ++this._globalTransformProcessStep;
  45362. this.updateCachedStates(false);
  45363. this._prepareGroupRender(context);
  45364. this._updateRenderId = this.scene.getRenderId();
  45365. };
  45366. /**
  45367. * Method that renders the Canvas, you should not invoke
  45368. */
  45369. Canvas2D.prototype._render = function () {
  45370. this._updateTrackedNodes();
  45371. this._updateCanvasState(false);
  45372. if (!this._isScreenSpace) {
  45373. this._updateAdaptiveSizeWorldCanvas();
  45374. }
  45375. this._updateCanvasState(false);
  45376. if (this._primPointerInfo.canvasPointerPos) {
  45377. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  45378. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  45379. }
  45380. this.engine.setState(false);
  45381. this._groupRender();
  45382. if (!this._isScreenSpace) {
  45383. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  45384. this.worldSpaceCacheChanged();
  45385. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  45386. }
  45387. }
  45388. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  45389. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  45390. this._cachedCanvasGroup._renderCachedCanvas();
  45391. }
  45392. };
  45393. /**
  45394. * Internal method that allocate a cache for the given group.
  45395. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  45396. * @param group The group to allocate the cache of.
  45397. * @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.
  45398. */
  45399. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  45400. if (useMipMap === void 0) { useMipMap = false; }
  45401. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  45402. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  45403. // Determine size
  45404. var size = group.actualSize;
  45405. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  45406. if (minSize) {
  45407. size.width = Math.max(minSize.width, size.width);
  45408. size.height = Math.max(minSize.height, size.height);
  45409. }
  45410. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  45411. // Try to find a spot in one of the cached texture
  45412. var res = null;
  45413. var map;
  45414. for (var _i = 0; _i < mapArray.length; _i++) {
  45415. var _map = mapArray[_i];
  45416. map = _map;
  45417. var node = map.allocateRect(size);
  45418. if (node) {
  45419. res = { node: node, texture: map };
  45420. break;
  45421. }
  45422. }
  45423. // Couldn't find a map that could fit the rect, create a new map for it
  45424. if (!res) {
  45425. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  45426. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  45427. if (size.width > mapSize.width || size.height > mapSize.height) {
  45428. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  45429. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  45430. }
  45431. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  45432. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  45433. map.anisotropicFilteringLevel = 4;
  45434. mapArray.splice(0, 0, map);
  45435. var node = map.allocateRect(size);
  45436. res = { node: node, texture: map };
  45437. }
  45438. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  45439. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  45440. if (group !== this || this._isScreenSpace) {
  45441. var node = res.node;
  45442. // 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
  45443. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  45444. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  45445. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  45446. sprite.zOrder = 1;
  45447. sprite.origin = BABYLON.Vector2.Zero();
  45448. }
  45449. else {
  45450. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  45451. sprite.origin = group.origin.clone();
  45452. res.sprite = sprite;
  45453. }
  45454. }
  45455. return res;
  45456. };
  45457. /**
  45458. * Internal method used to register a Scene Node to track position for the given group
  45459. * Do not invoke this method, for internal purpose only.
  45460. * @param group the group to track its associated Scene Node
  45461. */
  45462. Canvas2D.prototype._registerTrackedNode = function (group) {
  45463. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  45464. return;
  45465. }
  45466. this._trackedGroups.push(group);
  45467. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  45468. };
  45469. /**
  45470. * Internal method used to unregister a tracked Scene Node
  45471. * Do not invoke this method, it's for internal purpose only.
  45472. * @param group the group to unregister its tracked Scene Node from.
  45473. */
  45474. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  45475. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  45476. return;
  45477. }
  45478. var i = this._trackedGroups.indexOf(group);
  45479. if (i !== -1) {
  45480. this._trackedGroups.splice(i, 1);
  45481. }
  45482. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  45483. };
  45484. /**
  45485. * Get a Solid Color Brush instance matching the given color.
  45486. * @param color The color to retrieve
  45487. * @return A shared instance of the SolidColorBrush2D class that use the given color
  45488. */
  45489. Canvas2D.GetSolidColorBrush = function (color) {
  45490. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  45491. };
  45492. /**
  45493. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  45494. * @param color The color to retrieve
  45495. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  45496. */
  45497. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  45498. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  45499. };
  45500. /**
  45501. * Get a Gradient Color Brush
  45502. * @param color1 starting color
  45503. * @param color2 engine color
  45504. * @param translation translation vector to apply. default is [0;0]
  45505. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  45506. * @param scale scaling factor to apply. default is 1.
  45507. */
  45508. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  45509. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  45510. if (rotation === void 0) { rotation = 0; }
  45511. if (scale === void 0) { scale = 1; }
  45512. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  45513. };
  45514. /**
  45515. * Create a solid or gradient brush from a string value.
  45516. * @param brushString should be either
  45517. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  45518. * - "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.
  45519. */
  45520. Canvas2D.GetBrushFromString = function (brushString) {
  45521. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  45522. brushString = brushString.trim();
  45523. var split = brushString.split(",");
  45524. // Solid, formatted as: "[solid:]#FF808080"
  45525. if (split.length === 1) {
  45526. var value = null;
  45527. if (brushString.indexOf("solid:") === 0) {
  45528. value = brushString.substr(6).trim();
  45529. }
  45530. else if (brushString.indexOf("#") === 0) {
  45531. value = brushString;
  45532. }
  45533. else {
  45534. return null;
  45535. }
  45536. return Canvas2D.GetSolidColorBrushFromHex(value);
  45537. }
  45538. else {
  45539. if (split[0].indexOf("gradient:") === 0) {
  45540. split[0] = split[0].substr(9).trim();
  45541. }
  45542. try {
  45543. var start = BABYLON.Color4.FromHexString(split[0].trim());
  45544. var end = BABYLON.Color4.FromHexString(split[1].trim());
  45545. var t = BABYLON.Vector2.Zero();
  45546. if (split.length > 2) {
  45547. var v = split[2].trim();
  45548. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  45549. return null;
  45550. }
  45551. var sep = v.indexOf(":");
  45552. var x = parseFloat(v.substr(1, sep));
  45553. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  45554. t = new BABYLON.Vector2(x, y);
  45555. }
  45556. var r = 0;
  45557. if (split.length > 3) {
  45558. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  45559. }
  45560. var s = 1;
  45561. if (split.length > 4) {
  45562. s = parseFloat(split[4].trim());
  45563. }
  45564. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  45565. }
  45566. catch (e) {
  45567. return null;
  45568. }
  45569. }
  45570. };
  45571. /**
  45572. * 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.
  45573. * This strategy doesn't allow primitives added directly as children of the Canvas.
  45574. * 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.
  45575. */
  45576. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  45577. /**
  45578. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  45579. * 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.
  45580. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  45581. * 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.
  45582. */
  45583. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  45584. /**
  45585. * 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).
  45586. */
  45587. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  45588. /**
  45589. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  45590. * 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).
  45591. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  45592. */
  45593. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  45594. Canvas2D.hierarchyLevelMaxSiblingCount = 50;
  45595. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  45596. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  45597. Canvas2D._m = BABYLON.Matrix.Identity();
  45598. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  45599. /**
  45600. * Define the default size used for both the width and height of a MapTexture to allocate.
  45601. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  45602. */
  45603. Canvas2D._groupTextureCacheSize = 1024;
  45604. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  45605. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  45606. Canvas2D = __decorate([
  45607. BABYLON.className("Canvas2D")
  45608. ], Canvas2D);
  45609. return Canvas2D;
  45610. })(BABYLON.Group2D);
  45611. BABYLON.Canvas2D = Canvas2D;
  45612. var WorldSpaceCanvas2D = (function (_super) {
  45613. __extends(WorldSpaceCanvas2D, _super);
  45614. /**
  45615. * 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.
  45616. * 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.
  45617. * @param scene the Scene that owns the Canvas
  45618. * @param size the dimension of the Canvas in World Space
  45619. * @param settings a combination of settings, possible ones are
  45620. * - children: an array of direct children primitives
  45621. * - id: a text identifier, for information purpose only, default is null.
  45622. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  45623. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  45624. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  45625. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  45626. * - 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).
  45627. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  45628. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  45629. * - 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.
  45630. * - 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.
  45631. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  45632. * - 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.
  45633. * - 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.
  45634. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45635. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45636. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45637. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45638. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45639. */
  45640. function WorldSpaceCanvas2D(scene, size, settings) {
  45641. BABYLON.Prim2DBase._isCanvasInit = true;
  45642. var s = settings;
  45643. s.isScreenSpace = false;
  45644. s.size = size.clone();
  45645. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  45646. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  45647. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  45648. }
  45649. _super.call(this, scene, settings);
  45650. BABYLON.Prim2DBase._isCanvasInit = false;
  45651. this._renderableData._useMipMap = true;
  45652. this._renderableData._anisotropicLevel = 8;
  45653. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  45654. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  45655. //}
  45656. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  45657. var id = settings ? settings.id || null : null;
  45658. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  45659. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  45660. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  45661. if (settings.maxAdaptiveCanvasSize == null) {
  45662. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  45663. }
  45664. else {
  45665. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  45666. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  45667. }
  45668. if (createWorldSpaceNode) {
  45669. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  45670. var vertexData = BABYLON.VertexData.CreatePlane({
  45671. width: size.width,
  45672. height: size.height,
  45673. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  45674. });
  45675. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  45676. this.applyCachedTexture(vertexData, mtl);
  45677. vertexData.applyToMesh(plane, true);
  45678. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  45679. mtl.disableLighting = true;
  45680. mtl.useAlphaFromDiffuseTexture = true;
  45681. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  45682. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  45683. plane.material = mtl;
  45684. this._worldSpaceNode = plane;
  45685. }
  45686. else {
  45687. this._worldSpaceNode = settings.customWorldSpaceNode;
  45688. this.applyCachedTexture(null, null);
  45689. }
  45690. }
  45691. WorldSpaceCanvas2D = __decorate([
  45692. BABYLON.className("WorldSpaceCanvas2D")
  45693. ], WorldSpaceCanvas2D);
  45694. return WorldSpaceCanvas2D;
  45695. })(Canvas2D);
  45696. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  45697. var ScreenSpaceCanvas2D = (function (_super) {
  45698. __extends(ScreenSpaceCanvas2D, _super);
  45699. /**
  45700. * 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.
  45701. * 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.
  45702. * All caching strategies will be available.
  45703. * 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]
  45704. * @param scene the Scene that owns the Canvas
  45705. * @param settings a combination of settings, possible ones are
  45706. * - children: an array of direct children primitives
  45707. * - id: a text identifier, for information purpose only
  45708. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  45709. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  45710. * - 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]
  45711. * - width: the width of the Canvas. you can alternatively use the size setting.
  45712. * - height: the height of the Canvas. you can alternatively use the size setting.
  45713. * - 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
  45714. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  45715. * - 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.
  45716. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  45717. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  45718. * - 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.
  45719. * - 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.
  45720. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  45721. * - 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.
  45722. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45723. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45724. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45725. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  45726. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  45727. */
  45728. function ScreenSpaceCanvas2D(scene, settings) {
  45729. BABYLON.Prim2DBase._isCanvasInit = true;
  45730. _super.call(this, scene, settings);
  45731. }
  45732. ScreenSpaceCanvas2D = __decorate([
  45733. BABYLON.className("ScreenSpaceCanvas2D")
  45734. ], ScreenSpaceCanvas2D);
  45735. return ScreenSpaceCanvas2D;
  45736. })(Canvas2D);
  45737. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  45738. })(BABYLON || (BABYLON = {}));
  45739. var BABYLON;
  45740. (function (BABYLON) {
  45741. /**
  45742. * This is the class that is used to display a World Space Canvas into a 3D scene
  45743. */
  45744. var WorldSpaceCanvas2DNode = (function (_super) {
  45745. __extends(WorldSpaceCanvas2DNode, _super);
  45746. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  45747. _super.call(this, name, scene);
  45748. this._canvas = canvas;
  45749. }
  45750. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  45751. _super.prototype.dispose.call(this);
  45752. if (this._canvas) {
  45753. this._canvas.dispose();
  45754. this._canvas = null;
  45755. }
  45756. };
  45757. return WorldSpaceCanvas2DNode;
  45758. })(BABYLON.Mesh);
  45759. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  45760. })(BABYLON || (BABYLON = {}));
  45761. var BABYLON;
  45762. (function (BABYLON) {
  45763. var LayoutEngineBase = (function () {
  45764. function LayoutEngineBase() {
  45765. this.layoutDirtyOnPropertyChangedMask = 0;
  45766. }
  45767. LayoutEngineBase.prototype.updateLayout = function (prim) {
  45768. };
  45769. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  45770. get: function () {
  45771. return false;
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. LayoutEngineBase.prototype.isLocked = function () {
  45777. return this._isLocked;
  45778. };
  45779. LayoutEngineBase.prototype.lock = function () {
  45780. if (this._isLocked) {
  45781. return false;
  45782. }
  45783. this._isLocked = true;
  45784. return true;
  45785. };
  45786. LayoutEngineBase = __decorate([
  45787. BABYLON.className("LayoutEngineBase")
  45788. ], LayoutEngineBase);
  45789. return LayoutEngineBase;
  45790. })();
  45791. BABYLON.LayoutEngineBase = LayoutEngineBase;
  45792. var CanvasLayoutEngine = (function (_super) {
  45793. __extends(CanvasLayoutEngine, _super);
  45794. function CanvasLayoutEngine() {
  45795. _super.apply(this, arguments);
  45796. }
  45797. // A very simple (no) layout computing...
  45798. // The Canvas and its direct children gets the Canvas' size as Layout Area
  45799. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  45800. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  45801. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  45802. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  45803. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  45804. var child = _a[_i];
  45805. this._doUpdate(child);
  45806. }
  45807. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  45808. }
  45809. };
  45810. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  45811. // Canvas ?
  45812. if (prim instanceof BABYLON.Canvas2D) {
  45813. prim.layoutArea = prim.actualSize;
  45814. }
  45815. else if (prim.parent instanceof BABYLON.Canvas2D) {
  45816. prim.layoutArea = prim.owner.actualSize;
  45817. }
  45818. else {
  45819. prim.layoutArea = prim.parent.contentArea;
  45820. }
  45821. };
  45822. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  45823. get: function () {
  45824. return true;
  45825. },
  45826. enumerable: true,
  45827. configurable: true
  45828. });
  45829. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  45830. CanvasLayoutEngine = __decorate([
  45831. BABYLON.className("CanvasLayoutEngine")
  45832. ], CanvasLayoutEngine);
  45833. return CanvasLayoutEngine;
  45834. })(LayoutEngineBase);
  45835. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  45836. var StackPanelLayoutEngine = (function (_super) {
  45837. __extends(StackPanelLayoutEngine, _super);
  45838. function StackPanelLayoutEngine() {
  45839. _super.call(this);
  45840. this._isHorizontal = true;
  45841. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  45842. }
  45843. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  45844. get: function () {
  45845. if (!StackPanelLayoutEngine._horizontal) {
  45846. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  45847. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  45848. StackPanelLayoutEngine._horizontal.lock();
  45849. }
  45850. return StackPanelLayoutEngine._horizontal;
  45851. },
  45852. enumerable: true,
  45853. configurable: true
  45854. });
  45855. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  45856. get: function () {
  45857. if (!StackPanelLayoutEngine._vertical) {
  45858. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  45859. StackPanelLayoutEngine._vertical.isHorizontal = false;
  45860. StackPanelLayoutEngine._vertical.lock();
  45861. }
  45862. return StackPanelLayoutEngine._vertical;
  45863. },
  45864. enumerable: true,
  45865. configurable: true
  45866. });
  45867. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  45868. get: function () {
  45869. return this._isHorizontal;
  45870. },
  45871. set: function (val) {
  45872. if (this.isLocked()) {
  45873. return;
  45874. }
  45875. this._isHorizontal = val;
  45876. },
  45877. enumerable: true,
  45878. configurable: true
  45879. });
  45880. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  45881. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  45882. var x = 0;
  45883. var y = 0;
  45884. var h = this.isHorizontal;
  45885. var max = 0;
  45886. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  45887. var child = _a[_i];
  45888. var layoutArea = child.layoutArea;
  45889. child.margin.computeArea(child.actualSize, layoutArea);
  45890. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  45891. }
  45892. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  45893. var child = _c[_b];
  45894. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  45895. var layoutArea = child.layoutArea;
  45896. if (h) {
  45897. x += layoutArea.width;
  45898. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  45899. }
  45900. else {
  45901. y += layoutArea.height;
  45902. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  45903. }
  45904. }
  45905. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  45906. }
  45907. };
  45908. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  45909. get: function () {
  45910. return false;
  45911. },
  45912. enumerable: true,
  45913. configurable: true
  45914. });
  45915. StackPanelLayoutEngine._horizontal = null;
  45916. StackPanelLayoutEngine._vertical = null;
  45917. StackPanelLayoutEngine = __decorate([
  45918. BABYLON.className("StackPanelLayoutEngine")
  45919. ], StackPanelLayoutEngine);
  45920. return StackPanelLayoutEngine;
  45921. })(LayoutEngineBase);
  45922. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  45923. })(BABYLON || (BABYLON = {}));
  45924. var BABYLON;
  45925. (function (BABYLON) {
  45926. var ShaderMaterial = (function (_super) {
  45927. __extends(ShaderMaterial, _super);
  45928. function ShaderMaterial(name, scene, shaderPath, options) {
  45929. _super.call(this, name, scene);
  45930. this._textures = {};
  45931. this._textureArrays = {};
  45932. this._floats = {};
  45933. this._floatsArrays = {};
  45934. this._colors3 = {};
  45935. this._colors4 = {};
  45936. this._vectors2 = {};
  45937. this._vectors3 = {};
  45938. this._vectors4 = {};
  45939. this._matrices = {};
  45940. this._matrices3x3 = {};
  45941. this._matrices2x2 = {};
  45942. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  45943. this._shaderPath = shaderPath;
  45944. options.needAlphaBlending = options.needAlphaBlending || false;
  45945. options.needAlphaTesting = options.needAlphaTesting || false;
  45946. options.attributes = options.attributes || ["position", "normal", "uv"];
  45947. options.uniforms = options.uniforms || ["worldViewProjection"];
  45948. options.samplers = options.samplers || [];
  45949. options.defines = options.defines || [];
  45950. this._options = options;
  45951. }
  45952. ShaderMaterial.prototype.needAlphaBlending = function () {
  45953. return this._options.needAlphaBlending;
  45954. };
  45955. ShaderMaterial.prototype.needAlphaTesting = function () {
  45956. return this._options.needAlphaTesting;
  45957. };
  45958. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  45959. if (this._options.uniforms.indexOf(uniformName) === -1) {
  45960. this._options.uniforms.push(uniformName);
  45961. }
  45962. };
  45963. ShaderMaterial.prototype.setTexture = function (name, texture) {
  45964. if (this._options.samplers.indexOf(name) === -1) {
  45965. this._options.samplers.push(name);
  45966. }
  45967. this._textures[name] = texture;
  45968. return this;
  45969. };
  45970. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  45971. if (this._options.samplers.indexOf(name) === -1) {
  45972. this._options.samplers.push(name);
  45973. }
  45974. this._checkUniform(name);
  45975. this._textureArrays[name] = textures;
  45976. return this;
  45977. };
  45978. ShaderMaterial.prototype.setFloat = function (name, value) {
  45979. this._checkUniform(name);
  45980. this._floats[name] = value;
  45981. return this;
  45982. };
  45983. ShaderMaterial.prototype.setFloats = function (name, value) {
  45984. this._checkUniform(name);
  45985. this._floatsArrays[name] = value;
  45986. return this;
  45987. };
  45988. ShaderMaterial.prototype.setColor3 = function (name, value) {
  45989. this._checkUniform(name);
  45990. this._colors3[name] = value;
  45991. return this;
  45992. };
  45993. ShaderMaterial.prototype.setColor4 = function (name, value) {
  45994. this._checkUniform(name);
  45995. this._colors4[name] = value;
  45996. return this;
  45997. };
  45998. ShaderMaterial.prototype.setVector2 = function (name, value) {
  45999. this._checkUniform(name);
  46000. this._vectors2[name] = value;
  46001. return this;
  46002. };
  46003. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46004. this._checkUniform(name);
  46005. this._vectors3[name] = value;
  46006. return this;
  46007. };
  46008. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46009. this._checkUniform(name);
  46010. this._vectors4[name] = value;
  46011. return this;
  46012. };
  46013. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46014. this._checkUniform(name);
  46015. this._matrices[name] = value;
  46016. return this;
  46017. };
  46018. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46019. this._checkUniform(name);
  46020. this._matrices3x3[name] = value;
  46021. return this;
  46022. };
  46023. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46024. this._checkUniform(name);
  46025. this._matrices2x2[name] = value;
  46026. return this;
  46027. };
  46028. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46029. var scene = this.getScene();
  46030. var engine = scene.getEngine();
  46031. if (!this.checkReadyOnEveryCall) {
  46032. if (this._renderId === scene.getRenderId()) {
  46033. return true;
  46034. }
  46035. }
  46036. // Instances
  46037. var defines = [];
  46038. var fallbacks = new BABYLON.EffectFallbacks();
  46039. if (useInstances) {
  46040. defines.push("#define INSTANCES");
  46041. }
  46042. for (var index = 0; index < this._options.defines.length; index++) {
  46043. defines.push(this._options.defines[index]);
  46044. }
  46045. // Bones
  46046. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46047. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46048. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46049. fallbacks.addCPUSkinningFallback(0, mesh);
  46050. }
  46051. // Alpha test
  46052. if (engine.getAlphaTesting()) {
  46053. defines.push("#define ALPHATEST");
  46054. }
  46055. var previousEffect = this._effect;
  46056. var join = defines.join("\n");
  46057. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  46058. if (!this._effect.isReady()) {
  46059. return false;
  46060. }
  46061. if (previousEffect !== this._effect) {
  46062. scene.resetCachedMaterial();
  46063. }
  46064. this._renderId = scene.getRenderId();
  46065. return true;
  46066. };
  46067. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46068. var scene = this.getScene();
  46069. if (this._options.uniforms.indexOf("world") !== -1) {
  46070. this._effect.setMatrix("world", world);
  46071. }
  46072. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46073. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46074. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46075. }
  46076. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46077. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46078. }
  46079. };
  46080. ShaderMaterial.prototype.bind = function (world, mesh) {
  46081. // Std values
  46082. this.bindOnlyWorldMatrix(world);
  46083. if (this.getScene().getCachedMaterial() !== this) {
  46084. if (this._options.uniforms.indexOf("view") !== -1) {
  46085. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46086. }
  46087. if (this._options.uniforms.indexOf("projection") !== -1) {
  46088. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46089. }
  46090. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46091. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46092. }
  46093. // Bones
  46094. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46095. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46096. }
  46097. var name;
  46098. // Texture
  46099. for (name in this._textures) {
  46100. this._effect.setTexture(name, this._textures[name]);
  46101. }
  46102. // Texture arrays
  46103. for (name in this._textureArrays) {
  46104. this._effect.setTextureArray(name, this._textureArrays[name]);
  46105. }
  46106. // Float
  46107. for (name in this._floats) {
  46108. this._effect.setFloat(name, this._floats[name]);
  46109. }
  46110. // Float s
  46111. for (name in this._floatsArrays) {
  46112. this._effect.setArray(name, this._floatsArrays[name]);
  46113. }
  46114. // Color3
  46115. for (name in this._colors3) {
  46116. this._effect.setColor3(name, this._colors3[name]);
  46117. }
  46118. // Color4
  46119. for (name in this._colors4) {
  46120. var color = this._colors4[name];
  46121. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46122. }
  46123. // Vector2
  46124. for (name in this._vectors2) {
  46125. this._effect.setVector2(name, this._vectors2[name]);
  46126. }
  46127. // Vector3
  46128. for (name in this._vectors3) {
  46129. this._effect.setVector3(name, this._vectors3[name]);
  46130. }
  46131. // Vector4
  46132. for (name in this._vectors4) {
  46133. this._effect.setVector4(name, this._vectors4[name]);
  46134. }
  46135. // Matrix
  46136. for (name in this._matrices) {
  46137. this._effect.setMatrix(name, this._matrices[name]);
  46138. }
  46139. // Matrix 3x3
  46140. for (name in this._matrices3x3) {
  46141. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46142. }
  46143. // Matrix 2x2
  46144. for (name in this._matrices2x2) {
  46145. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46146. }
  46147. }
  46148. _super.prototype.bind.call(this, world, mesh);
  46149. };
  46150. ShaderMaterial.prototype.clone = function (name) {
  46151. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46152. return newShaderMaterial;
  46153. };
  46154. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46155. if (forceDisposeTextures) {
  46156. var name;
  46157. for (name in this._textures) {
  46158. this._textures[name].dispose();
  46159. }
  46160. for (name in this._textureArrays) {
  46161. var array = this._textureArrays[name];
  46162. for (var index = 0; index < array.length; index++) {
  46163. array[index].dispose();
  46164. }
  46165. }
  46166. }
  46167. this._textures = {};
  46168. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46169. };
  46170. ShaderMaterial.prototype.serialize = function () {
  46171. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46172. serializationObject.customType = "BABYLON.ShaderMaterial";
  46173. serializationObject.options = this._options;
  46174. serializationObject.shaderPath = this._shaderPath;
  46175. var name;
  46176. // Texture
  46177. serializationObject.textures = {};
  46178. for (name in this._textures) {
  46179. serializationObject.textures[name] = this._textures[name].serialize();
  46180. }
  46181. // Texture arrays
  46182. serializationObject.textureArrays = {};
  46183. for (name in this._textureArrays) {
  46184. serializationObject.textureArrays[name] = [];
  46185. var array = this._textureArrays[name];
  46186. for (var index = 0; index < array.length; index++) {
  46187. serializationObject.textureArrays[name].push(array[index].serialize());
  46188. }
  46189. }
  46190. // Float
  46191. serializationObject.floats = {};
  46192. for (name in this._floats) {
  46193. serializationObject.floats[name] = this._floats[name];
  46194. }
  46195. // Float s
  46196. serializationObject.floatArrays = {};
  46197. for (name in this._floatsArrays) {
  46198. serializationObject.floatArrays[name] = this._floatsArrays[name];
  46199. }
  46200. // Color3
  46201. serializationObject.colors3 = {};
  46202. for (name in this._colors3) {
  46203. serializationObject.colors3[name] = this._colors3[name].asArray();
  46204. }
  46205. // Color4
  46206. serializationObject.colors4 = {};
  46207. for (name in this._colors4) {
  46208. serializationObject.colors4[name] = this._colors4[name].asArray();
  46209. }
  46210. // Vector2
  46211. serializationObject.vectors2 = {};
  46212. for (name in this._vectors2) {
  46213. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46214. }
  46215. // Vector3
  46216. serializationObject.vectors3 = {};
  46217. for (name in this._vectors3) {
  46218. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46219. }
  46220. // Vector4
  46221. serializationObject.vectors4 = {};
  46222. for (name in this._vectors4) {
  46223. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46224. }
  46225. // Matrix
  46226. serializationObject.matrices = {};
  46227. for (name in this._matrices) {
  46228. serializationObject.matrices[name] = this._matrices[name].asArray();
  46229. }
  46230. // Matrix 3x3
  46231. serializationObject.matrices3x3 = {};
  46232. for (name in this._matrices3x3) {
  46233. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46234. }
  46235. // Matrix 2x2
  46236. serializationObject.matrices2x2 = {};
  46237. for (name in this._matrices2x2) {
  46238. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46239. }
  46240. return serializationObject;
  46241. };
  46242. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46243. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46244. var name;
  46245. // Texture
  46246. for (name in source.textures) {
  46247. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46248. }
  46249. // Texture arrays
  46250. for (name in source.textureArrays) {
  46251. var array = source.textureArrays[name];
  46252. var textureArray = new Array();
  46253. for (var index = 0; index < array.length; index++) {
  46254. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46255. }
  46256. material.setTextureArray(name, textureArray);
  46257. }
  46258. // Float
  46259. for (name in source.floats) {
  46260. material.setFloat(name, source.floats[name]);
  46261. }
  46262. // Float s
  46263. for (name in source.floatsArrays) {
  46264. material.setFloats(name, source.floatsArrays[name]);
  46265. }
  46266. // Color3
  46267. for (name in source.colors3) {
  46268. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46269. }
  46270. // Color4
  46271. for (name in source.colors4) {
  46272. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46273. }
  46274. // Vector2
  46275. for (name in source.vectors2) {
  46276. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46277. }
  46278. // Vector3
  46279. for (name in source.vectors3) {
  46280. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46281. }
  46282. // Vector4
  46283. for (name in source.vectors4) {
  46284. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46285. }
  46286. // Matrix
  46287. for (name in source.matrices) {
  46288. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46289. }
  46290. // Matrix 3x3
  46291. for (name in source.matrices3x3) {
  46292. material.setMatrix3x3(name, source.matrices3x3[name]);
  46293. }
  46294. // Matrix 2x2
  46295. for (name in source.matrices2x2) {
  46296. material.setMatrix2x2(name, source.matrices2x2[name]);
  46297. }
  46298. return material;
  46299. };
  46300. return ShaderMaterial;
  46301. })(BABYLON.Material);
  46302. BABYLON.ShaderMaterial = ShaderMaterial;
  46303. })(BABYLON || (BABYLON = {}));
  46304. var BABYLON;
  46305. (function (BABYLON) {
  46306. var Internals;
  46307. (function (Internals) {
  46308. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  46309. // All values and structures referenced from:
  46310. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  46311. var DDS_MAGIC = 0x20534444;
  46312. 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;
  46313. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  46314. 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;
  46315. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  46316. function FourCCToInt32(value) {
  46317. return value.charCodeAt(0) +
  46318. (value.charCodeAt(1) << 8) +
  46319. (value.charCodeAt(2) << 16) +
  46320. (value.charCodeAt(3) << 24);
  46321. }
  46322. function Int32ToFourCC(value) {
  46323. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  46324. }
  46325. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  46326. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  46327. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  46328. var headerLengthInt = 31; // The header length in 32 bit ints
  46329. // Offsets into the header array
  46330. var off_magic = 0;
  46331. var off_size = 1;
  46332. var off_flags = 2;
  46333. var off_height = 3;
  46334. var off_width = 4;
  46335. var off_mipmapCount = 7;
  46336. var off_pfFlags = 20;
  46337. var off_pfFourCC = 21;
  46338. var off_RGBbpp = 22;
  46339. var off_RMask = 23;
  46340. var off_GMask = 24;
  46341. var off_BMask = 25;
  46342. var off_AMask = 26;
  46343. var off_caps1 = 27;
  46344. var off_caps2 = 28;
  46345. ;
  46346. var DDSTools = (function () {
  46347. function DDSTools() {
  46348. }
  46349. DDSTools.GetDDSInfo = function (arrayBuffer) {
  46350. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  46351. var mipmapCount = 1;
  46352. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  46353. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46354. }
  46355. return {
  46356. width: header[off_width],
  46357. height: header[off_height],
  46358. mipmapCount: mipmapCount,
  46359. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  46360. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  46361. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  46362. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  46363. };
  46364. };
  46365. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46366. var byteArray = new Uint8Array(dataLength);
  46367. var srcData = new Uint8Array(arrayBuffer);
  46368. var index = 0;
  46369. for (var y = height - 1; y >= 0; y--) {
  46370. for (var x = 0; x < width; x++) {
  46371. var srcPos = dataOffset + (x + y * width) * 4;
  46372. byteArray[index + 2] = srcData[srcPos];
  46373. byteArray[index + 1] = srcData[srcPos + 1];
  46374. byteArray[index] = srcData[srcPos + 2];
  46375. byteArray[index + 3] = srcData[srcPos + 3];
  46376. index += 4;
  46377. }
  46378. }
  46379. return byteArray;
  46380. };
  46381. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46382. var byteArray = new Uint8Array(dataLength);
  46383. var srcData = new Uint8Array(arrayBuffer);
  46384. var index = 0;
  46385. for (var y = height - 1; y >= 0; y--) {
  46386. for (var x = 0; x < width; x++) {
  46387. var srcPos = dataOffset + (x + y * width) * 3;
  46388. byteArray[index + 2] = srcData[srcPos];
  46389. byteArray[index + 1] = srcData[srcPos + 1];
  46390. byteArray[index] = srcData[srcPos + 2];
  46391. index += 3;
  46392. }
  46393. }
  46394. return byteArray;
  46395. };
  46396. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46397. var byteArray = new Uint8Array(dataLength);
  46398. var srcData = new Uint8Array(arrayBuffer);
  46399. var index = 0;
  46400. for (var y = height - 1; y >= 0; y--) {
  46401. for (var x = 0; x < width; x++) {
  46402. var srcPos = dataOffset + (x + y * width);
  46403. byteArray[index] = srcData[srcPos];
  46404. index++;
  46405. }
  46406. }
  46407. return byteArray;
  46408. };
  46409. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  46410. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  46411. if (header[off_magic] != DDS_MAGIC) {
  46412. BABYLON.Tools.Error("Invalid magic number in DDS header");
  46413. return;
  46414. }
  46415. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  46416. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  46417. return;
  46418. }
  46419. if (info.isFourCC) {
  46420. fourCC = header[off_pfFourCC];
  46421. switch (fourCC) {
  46422. case FOURCC_DXT1:
  46423. blockBytes = 8;
  46424. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46425. break;
  46426. case FOURCC_DXT3:
  46427. blockBytes = 16;
  46428. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46429. break;
  46430. case FOURCC_DXT5:
  46431. blockBytes = 16;
  46432. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46433. break;
  46434. default:
  46435. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  46436. return;
  46437. }
  46438. }
  46439. mipmapCount = 1;
  46440. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  46441. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46442. }
  46443. var bpp = header[off_RGBbpp];
  46444. for (var face = 0; face < faces; face++) {
  46445. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46446. width = header[off_width];
  46447. height = header[off_height];
  46448. dataOffset = header[off_size] + 4;
  46449. for (i = 0; i < mipmapCount; ++i) {
  46450. if (info.isRGB) {
  46451. if (bpp === 24) {
  46452. dataLength = width * height * 3;
  46453. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46454. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  46455. }
  46456. else {
  46457. dataLength = width * height * 4;
  46458. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46459. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  46460. }
  46461. }
  46462. else if (info.isLuminance) {
  46463. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  46464. var unpaddedRowSize = width;
  46465. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  46466. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  46467. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46468. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  46469. }
  46470. else {
  46471. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  46472. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  46473. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  46474. }
  46475. dataOffset += dataLength;
  46476. width *= 0.5;
  46477. height *= 0.5;
  46478. width = Math.max(1.0, width);
  46479. height = Math.max(1.0, height);
  46480. }
  46481. }
  46482. };
  46483. return DDSTools;
  46484. })();
  46485. Internals.DDSTools = DDSTools;
  46486. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46487. })(BABYLON || (BABYLON = {}));
  46488. var BABYLON;
  46489. (function (BABYLON) {
  46490. var CannonJSPlugin = (function () {
  46491. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  46492. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  46493. if (iterations === void 0) { iterations = 10; }
  46494. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  46495. this.name = "CannonJSPlugin";
  46496. this._physicsMaterials = [];
  46497. this._fixedTimeStep = 1 / 60;
  46498. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  46499. this._currentCollisionGroup = 2;
  46500. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  46501. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  46502. this._tmpPosition = BABYLON.Vector3.Zero();
  46503. this._tmpQuaternion = new BABYLON.Quaternion();
  46504. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  46505. this._tmpDeltaRotation = new BABYLON.Quaternion();
  46506. this._tmpUnityRotation = new BABYLON.Quaternion();
  46507. if (!this.isSupported()) {
  46508. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  46509. return;
  46510. }
  46511. this.world = new CANNON.World();
  46512. this.world.broadphase = new CANNON.NaiveBroadphase();
  46513. this.world.solver.iterations = iterations;
  46514. }
  46515. CannonJSPlugin.prototype.setGravity = function (gravity) {
  46516. this.world.gravity.copy(gravity);
  46517. };
  46518. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  46519. this._fixedTimeStep = timeStep;
  46520. };
  46521. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  46522. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  46523. };
  46524. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46525. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46526. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46527. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  46528. };
  46529. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46530. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  46531. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  46532. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  46533. };
  46534. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46535. //parent-child relationship. Does this impostor has a parent impostor?
  46536. if (impostor.parent) {
  46537. if (impostor.physicsBody) {
  46538. this.removePhysicsBody(impostor);
  46539. //TODO is that needed?
  46540. impostor.forceUpdate();
  46541. }
  46542. return;
  46543. }
  46544. //should a new body be created for this impostor?
  46545. if (impostor.isBodyInitRequired()) {
  46546. var shape = this._createShape(impostor);
  46547. //unregister events, if body is being changed
  46548. var oldBody = impostor.physicsBody;
  46549. if (oldBody) {
  46550. this.removePhysicsBody(impostor);
  46551. }
  46552. //create the body and material
  46553. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  46554. var bodyCreationObject = {
  46555. mass: impostor.getParam("mass"),
  46556. material: material
  46557. };
  46558. // A simple extend, in case native options were used.
  46559. var nativeOptions = impostor.getParam("nativeOptions");
  46560. for (var key in nativeOptions) {
  46561. if (nativeOptions.hasOwnProperty(key)) {
  46562. bodyCreationObject[key] = nativeOptions[key];
  46563. }
  46564. }
  46565. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  46566. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  46567. this.world.addEventListener("preStep", impostor.beforeStep);
  46568. this.world.addEventListener("postStep", impostor.afterStep);
  46569. impostor.physicsBody.addShape(shape);
  46570. this.world.add(impostor.physicsBody);
  46571. //try to keep the body moving in the right direction by taking old properties.
  46572. //Should be tested!
  46573. if (oldBody) {
  46574. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  46575. impostor.physicsBody[param].copy(oldBody[param]);
  46576. });
  46577. }
  46578. this._processChildMeshes(impostor);
  46579. }
  46580. //now update the body's transformation
  46581. this._updatePhysicsBodyTransformation(impostor);
  46582. };
  46583. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  46584. var _this = this;
  46585. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  46586. if (meshChildren.length) {
  46587. var processMesh = function (localPosition, mesh) {
  46588. var childImpostor = mesh.getPhysicsImpostor();
  46589. if (childImpostor) {
  46590. var parent = childImpostor.parent;
  46591. if (parent !== mainImpostor) {
  46592. var localPosition = mesh.position;
  46593. if (childImpostor.physicsBody) {
  46594. _this.removePhysicsBody(childImpostor);
  46595. childImpostor.physicsBody = null;
  46596. }
  46597. childImpostor.parent = mainImpostor;
  46598. childImpostor.resetUpdateFlags();
  46599. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  46600. //Add the mass of the children.
  46601. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  46602. }
  46603. }
  46604. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  46605. };
  46606. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  46607. }
  46608. };
  46609. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46610. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  46611. this.world.removeEventListener("preStep", impostor.beforeStep);
  46612. this.world.removeEventListener("postStep", impostor.afterStep);
  46613. this.world.remove(impostor.physicsBody);
  46614. };
  46615. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46616. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46617. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46618. if (!mainBody || !connectedBody) {
  46619. return;
  46620. }
  46621. var constraint;
  46622. var jointData = impostorJoint.joint.jointData;
  46623. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  46624. var constraintData = {
  46625. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  46626. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  46627. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  46628. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  46629. maxForce: jointData.nativeParams.maxForce,
  46630. collideConnected: !!jointData.collision
  46631. };
  46632. //Not needed, Cannon has a collideConnected flag
  46633. /*if (!jointData.collision) {
  46634. //add 1st body to a collision group of its own, if it is not in 1
  46635. if (mainBody.collisionFilterGroup === 1) {
  46636. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  46637. this._currentCollisionGroup <<= 1;
  46638. }
  46639. if (connectedBody.collisionFilterGroup === 1) {
  46640. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  46641. this._currentCollisionGroup <<= 1;
  46642. }
  46643. //add their mask to the collisionFilterMask of each other:
  46644. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  46645. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  46646. }*/
  46647. switch (impostorJoint.joint.type) {
  46648. case BABYLON.PhysicsJoint.HingeJoint:
  46649. case BABYLON.PhysicsJoint.Hinge2Joint:
  46650. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  46651. break;
  46652. case BABYLON.PhysicsJoint.DistanceJoint:
  46653. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  46654. break;
  46655. case BABYLON.PhysicsJoint.SpringJoint:
  46656. var springData = jointData;
  46657. constraint = new CANNON.Spring(mainBody, connectedBody, {
  46658. restLength: springData.length,
  46659. stiffness: springData.stiffness,
  46660. damping: springData.damping,
  46661. localAnchorA: constraintData.pivotA,
  46662. localAnchorB: constraintData.pivotB
  46663. });
  46664. break;
  46665. case BABYLON.PhysicsJoint.LockJoint:
  46666. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  46667. break;
  46668. case BABYLON.PhysicsJoint.PointToPointJoint:
  46669. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46670. default:
  46671. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  46672. break;
  46673. }
  46674. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  46675. constraint.collideConnected = !!jointData.collision;
  46676. impostorJoint.joint.physicsJoint = constraint;
  46677. //don't add spring as constraint, as it is not one.
  46678. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  46679. this.world.addConstraint(constraint);
  46680. }
  46681. else {
  46682. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  46683. constraint.applyForce();
  46684. });
  46685. }
  46686. };
  46687. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46688. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  46689. };
  46690. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  46691. var index;
  46692. var mat;
  46693. for (index = 0; index < this._physicsMaterials.length; index++) {
  46694. mat = this._physicsMaterials[index];
  46695. if (mat.friction === friction && mat.restitution === restitution) {
  46696. return mat;
  46697. }
  46698. }
  46699. var currentMat = new CANNON.Material(name);
  46700. currentMat.friction = friction;
  46701. currentMat.restitution = restitution;
  46702. this._physicsMaterials.push(currentMat);
  46703. return currentMat;
  46704. };
  46705. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  46706. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  46707. };
  46708. CannonJSPlugin.prototype._createShape = function (impostor) {
  46709. var object = impostor.object;
  46710. var returnValue;
  46711. var extendSize = impostor.getObjectExtendSize();
  46712. switch (impostor.type) {
  46713. case BABYLON.PhysicsEngine.SphereImpostor:
  46714. var radiusX = extendSize.x;
  46715. var radiusY = extendSize.y;
  46716. var radiusZ = extendSize.z;
  46717. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  46718. break;
  46719. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  46720. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46721. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  46722. break;
  46723. case BABYLON.PhysicsImpostor.BoxImpostor:
  46724. var box = extendSize.scale(0.5);
  46725. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  46726. break;
  46727. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46728. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  46729. returnValue = new CANNON.Plane();
  46730. break;
  46731. case BABYLON.PhysicsImpostor.MeshImpostor:
  46732. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  46733. var rawFaces = object.getIndices ? object.getIndices() : [];
  46734. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  46735. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  46736. break;
  46737. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  46738. returnValue = this._createHeightmap(object);
  46739. break;
  46740. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46741. returnValue = new CANNON.Particle();
  46742. break;
  46743. }
  46744. return returnValue;
  46745. };
  46746. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  46747. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46748. var matrix = [];
  46749. //For now pointDepth will not be used and will be automatically calculated.
  46750. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  46751. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  46752. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  46753. var elementSize = dim * 2 / arraySize;
  46754. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  46755. for (var i = 0; i < pos.length; i = i + 3) {
  46756. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  46757. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  46758. var y = pos[i + 1] + minY;
  46759. if (!matrix[x]) {
  46760. matrix[x] = [];
  46761. }
  46762. if (!matrix[x][z]) {
  46763. matrix[x][z] = y;
  46764. }
  46765. matrix[x][z] = Math.max(y, matrix[x][z]);
  46766. }
  46767. for (var x = 0; x <= arraySize; ++x) {
  46768. if (!matrix[x]) {
  46769. var loc = 1;
  46770. while (!matrix[(x + loc) % arraySize]) {
  46771. loc++;
  46772. }
  46773. matrix[x] = matrix[(x + loc) % arraySize].slice();
  46774. }
  46775. for (var z = 0; z <= arraySize; ++z) {
  46776. if (!matrix[x][z]) {
  46777. var loc = 1;
  46778. var newValue;
  46779. while (newValue === undefined) {
  46780. newValue = matrix[x][(z + loc++) % arraySize];
  46781. }
  46782. matrix[x][z] = newValue;
  46783. }
  46784. }
  46785. }
  46786. var shape = new CANNON.Heightfield(matrix, {
  46787. elementSize: elementSize
  46788. });
  46789. //For future reference, needed for body transformation
  46790. shape.minY = minY;
  46791. return shape;
  46792. };
  46793. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  46794. var object = impostor.object;
  46795. //make sure it is updated...
  46796. object.computeWorldMatrix && object.computeWorldMatrix(true);
  46797. // The delta between the mesh position and the mesh bounding box center
  46798. var center = impostor.getObjectCenter();
  46799. var extendSize = impostor.getObjectExtendSize();
  46800. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  46801. this._tmpPosition.copyFrom(center);
  46802. var quaternion = object.rotationQuaternion;
  46803. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  46804. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  46805. //-90 DEG in X, precalculated
  46806. quaternion = quaternion.multiply(this._minus90X);
  46807. //Invert! (Precalculated, 90 deg in X)
  46808. //No need to clone. this will never change.
  46809. impostor.setDeltaRotation(this._plus90X);
  46810. }
  46811. //If it is a heightfield, if should be centered.
  46812. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  46813. var mesh = object;
  46814. //calculate the correct body position:
  46815. var rotationQuaternion = mesh.rotationQuaternion;
  46816. mesh.rotationQuaternion = this._tmpUnityRotation;
  46817. mesh.computeWorldMatrix(true);
  46818. //get original center with no rotation
  46819. var c = center.clone();
  46820. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  46821. //rotation is back
  46822. mesh.rotationQuaternion = rotationQuaternion;
  46823. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  46824. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  46825. mesh.setPivotMatrix(p);
  46826. mesh.computeWorldMatrix(true);
  46827. //calculate the translation
  46828. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  46829. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  46830. //add it inverted to the delta
  46831. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  46832. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  46833. mesh.setPivotMatrix(oldPivot);
  46834. mesh.computeWorldMatrix(true);
  46835. }
  46836. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  46837. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  46838. this._tmpPosition.copyFrom(object.position);
  46839. }
  46840. impostor.setDeltaPosition(this._tmpDeltaPosition);
  46841. //Now update the impostor object
  46842. impostor.physicsBody.position.copy(this._tmpPosition);
  46843. impostor.physicsBody.quaternion.copy(quaternion);
  46844. };
  46845. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46846. impostor.object.position.copyFrom(impostor.physicsBody.position);
  46847. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  46848. };
  46849. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46850. impostor.physicsBody.position.copy(newPosition);
  46851. impostor.physicsBody.quaternion.copy(newRotation);
  46852. };
  46853. CannonJSPlugin.prototype.isSupported = function () {
  46854. return window.CANNON !== undefined;
  46855. };
  46856. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46857. impostor.physicsBody.velocity.copy(velocity);
  46858. };
  46859. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46860. impostor.physicsBody.angularVelocity.copy(velocity);
  46861. };
  46862. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46863. var v = impostor.physicsBody.velocity;
  46864. if (!v)
  46865. return null;
  46866. return new BABYLON.Vector3(v.x, v.y, v.z);
  46867. };
  46868. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46869. var v = impostor.physicsBody.angularVelocity;
  46870. if (!v)
  46871. return null;
  46872. return new BABYLON.Vector3(v.x, v.y, v.z);
  46873. };
  46874. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46875. impostor.physicsBody.mass = mass;
  46876. impostor.physicsBody.updateMassProperties();
  46877. };
  46878. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  46879. impostor.physicsBody.sleep();
  46880. };
  46881. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  46882. impostor.physicsBody.wakeUp();
  46883. };
  46884. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46885. joint.physicsJoint.distance = maxDistance;
  46886. };
  46887. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  46888. if (!motorIndex) {
  46889. joint.physicsJoint.enableMotor();
  46890. }
  46891. };
  46892. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  46893. if (!motorIndex) {
  46894. joint.physicsJoint.disableMotor();
  46895. }
  46896. };
  46897. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46898. if (!motorIndex) {
  46899. joint.physicsJoint.enableMotor();
  46900. joint.physicsJoint.setMotorSpeed(speed);
  46901. if (maxForce) {
  46902. this.setLimit(joint, maxForce);
  46903. }
  46904. }
  46905. };
  46906. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  46907. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  46908. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  46909. };
  46910. CannonJSPlugin.prototype.dispose = function () {
  46911. //nothing to do, actually.
  46912. };
  46913. return CannonJSPlugin;
  46914. })();
  46915. BABYLON.CannonJSPlugin = CannonJSPlugin;
  46916. })(BABYLON || (BABYLON = {}));
  46917. var BABYLON;
  46918. (function (BABYLON) {
  46919. var OimoJSPlugin = (function () {
  46920. function OimoJSPlugin(iterations) {
  46921. this.name = "OimoJSPlugin";
  46922. this._tmpImpostorsArray = [];
  46923. this._tmpPositionVector = BABYLON.Vector3.Zero();
  46924. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  46925. this.world.clear();
  46926. //making sure no stats are calculated
  46927. this.world.isNoStat = true;
  46928. }
  46929. OimoJSPlugin.prototype.setGravity = function (gravity) {
  46930. this.world.gravity.copy(gravity);
  46931. };
  46932. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  46933. this.world.timeStep = timeStep;
  46934. };
  46935. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  46936. var _this = this;
  46937. impostors.forEach(function (impostor) {
  46938. impostor.beforeStep();
  46939. });
  46940. this.world.step();
  46941. impostors.forEach(function (impostor) {
  46942. impostor.afterStep();
  46943. //update the ordered impostors array
  46944. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  46945. });
  46946. //check for collisions
  46947. var contact = this.world.contacts;
  46948. while (contact !== null) {
  46949. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  46950. contact = contact.next;
  46951. continue;
  46952. }
  46953. //is this body colliding with any other? get the impostor
  46954. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  46955. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  46956. if (!mainImpostor || !collidingImpostor) {
  46957. contact = contact.next;
  46958. continue;
  46959. }
  46960. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  46961. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46962. contact = contact.next;
  46963. }
  46964. };
  46965. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46966. var mass = impostor.physicsBody.massInfo.mass;
  46967. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  46968. };
  46969. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46970. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  46971. this.applyImpulse(impostor, force, contactPoint);
  46972. };
  46973. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46974. var _this = this;
  46975. //parent-child relationship. Does this impostor has a parent impostor?
  46976. if (impostor.parent) {
  46977. if (impostor.physicsBody) {
  46978. this.removePhysicsBody(impostor);
  46979. //TODO is that needed?
  46980. impostor.forceUpdate();
  46981. }
  46982. return;
  46983. }
  46984. if (impostor.isBodyInitRequired()) {
  46985. var bodyConfig = {
  46986. name: impostor.uniqueId,
  46987. //Oimo must have mass, also for static objects.
  46988. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  46989. size: [],
  46990. type: [],
  46991. pos: [],
  46992. rot: [],
  46993. move: impostor.getParam("mass") !== 0,
  46994. //Supporting older versions of Oimo
  46995. world: this.world
  46996. };
  46997. var impostors = [impostor];
  46998. function addToArray(parent) {
  46999. if (!parent.getChildMeshes)
  47000. return;
  47001. parent.getChildMeshes().forEach(function (m) {
  47002. if (m.physicsImpostor) {
  47003. impostors.push(m.physicsImpostor);
  47004. m.physicsImpostor._init();
  47005. }
  47006. });
  47007. }
  47008. addToArray(impostor.object);
  47009. function checkWithEpsilon(value) {
  47010. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  47011. }
  47012. impostors.forEach(function (i) {
  47013. //get the correct bounding box
  47014. var oldQuaternion = i.object.rotationQuaternion;
  47015. var rot = new OIMO.Euler().setFromQuaternion({
  47016. x: impostor.object.rotationQuaternion.x,
  47017. y: impostor.object.rotationQuaternion.y,
  47018. z: impostor.object.rotationQuaternion.z,
  47019. s: impostor.object.rotationQuaternion.w
  47020. });
  47021. var extendSize = i.getObjectExtendSize();
  47022. if (i === impostor) {
  47023. var center = impostor.getObjectCenter();
  47024. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  47025. //Can also use Array.prototype.push.apply
  47026. bodyConfig.pos.push(center.x);
  47027. bodyConfig.pos.push(center.y);
  47028. bodyConfig.pos.push(center.z);
  47029. //tmp solution
  47030. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  47031. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  47032. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  47033. }
  47034. else {
  47035. bodyConfig.pos.push(i.object.position.x);
  47036. bodyConfig.pos.push(i.object.position.y);
  47037. bodyConfig.pos.push(i.object.position.z);
  47038. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  47039. bodyConfig.rot.push(0);
  47040. bodyConfig.rot.push(0);
  47041. bodyConfig.rot.push(0);
  47042. }
  47043. // register mesh
  47044. switch (i.type) {
  47045. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47046. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  47047. case BABYLON.PhysicsImpostor.SphereImpostor:
  47048. var radiusX = extendSize.x;
  47049. var radiusY = extendSize.y;
  47050. var radiusZ = extendSize.z;
  47051. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  47052. bodyConfig.type.push('sphere');
  47053. //due to the way oimo works with compounds, add 3 times
  47054. bodyConfig.size.push(size);
  47055. bodyConfig.size.push(size);
  47056. bodyConfig.size.push(size);
  47057. break;
  47058. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47059. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  47060. var sizeY = checkWithEpsilon(extendSize.y);
  47061. bodyConfig.type.push('cylinder');
  47062. bodyConfig.size.push(sizeX);
  47063. bodyConfig.size.push(sizeY);
  47064. //due to the way oimo works with compounds, add one more value.
  47065. bodyConfig.size.push(sizeY);
  47066. break;
  47067. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47068. case BABYLON.PhysicsImpostor.BoxImpostor:
  47069. default:
  47070. var sizeX = checkWithEpsilon(extendSize.x);
  47071. var sizeY = checkWithEpsilon(extendSize.y);
  47072. var sizeZ = checkWithEpsilon(extendSize.z);
  47073. bodyConfig.type.push('box');
  47074. bodyConfig.size.push(sizeX);
  47075. bodyConfig.size.push(sizeY);
  47076. bodyConfig.size.push(sizeZ);
  47077. break;
  47078. }
  47079. //actually not needed, but hey...
  47080. i.object.rotationQuaternion = oldQuaternion;
  47081. });
  47082. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  47083. }
  47084. else {
  47085. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  47086. }
  47087. impostor.setDeltaPosition(this._tmpPositionVector);
  47088. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  47089. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  47090. };
  47091. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47092. //impostor.physicsBody.dispose();
  47093. //Same as : (older oimo versions)
  47094. this.world.removeRigidBody(impostor.physicsBody);
  47095. };
  47096. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47097. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47098. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47099. if (!mainBody || !connectedBody) {
  47100. return;
  47101. }
  47102. var jointData = impostorJoint.joint.jointData;
  47103. var options = jointData.nativeParams || {};
  47104. var type;
  47105. var nativeJointData = {
  47106. body1: mainBody,
  47107. body2: connectedBody,
  47108. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  47109. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  47110. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  47111. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  47112. min: options.min,
  47113. max: options.max,
  47114. collision: options.collision || jointData.collision,
  47115. spring: options.spring,
  47116. //supporting older version of Oimo
  47117. world: this.world
  47118. };
  47119. switch (impostorJoint.joint.type) {
  47120. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47121. type = "jointBall";
  47122. break;
  47123. case BABYLON.PhysicsJoint.SpringJoint:
  47124. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  47125. var springData = jointData;
  47126. nativeJointData.min = springData.length || nativeJointData.min;
  47127. //Max should also be set, just make sure it is at least min
  47128. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  47129. case BABYLON.PhysicsJoint.DistanceJoint:
  47130. type = "jointDistance";
  47131. nativeJointData.max = jointData.maxDistance;
  47132. break;
  47133. case BABYLON.PhysicsJoint.PrismaticJoint:
  47134. type = "jointPrisme";
  47135. break;
  47136. case BABYLON.PhysicsJoint.SliderJoint:
  47137. type = "jointSlide";
  47138. break;
  47139. case BABYLON.PhysicsJoint.WheelJoint:
  47140. type = "jointWheel";
  47141. break;
  47142. case BABYLON.PhysicsJoint.HingeJoint:
  47143. default:
  47144. type = "jointHinge";
  47145. break;
  47146. }
  47147. nativeJointData.type = type;
  47148. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  47149. };
  47150. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47151. //Bug in Oimo prevents us from disposing a joint in the playground
  47152. //joint.joint.physicsJoint.dispose();
  47153. //So we will bruteforce it!
  47154. try {
  47155. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  47156. }
  47157. catch (e) {
  47158. BABYLON.Tools.Warn(e);
  47159. }
  47160. };
  47161. OimoJSPlugin.prototype.isSupported = function () {
  47162. return OIMO !== undefined;
  47163. };
  47164. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47165. if (!impostor.physicsBody.sleeping) {
  47166. //TODO check that
  47167. if (impostor.physicsBody.shapes.next) {
  47168. var parentShape = this._getLastShape(impostor.physicsBody);
  47169. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  47170. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  47171. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  47172. }
  47173. else {
  47174. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  47175. }
  47176. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  47177. impostor.object.rotationQuaternion.normalize();
  47178. }
  47179. };
  47180. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47181. var body = impostor.physicsBody;
  47182. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  47183. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  47184. body.syncShapes();
  47185. body.awake();
  47186. };
  47187. OimoJSPlugin.prototype._getLastShape = function (body) {
  47188. var lastShape = body.shapes;
  47189. while (lastShape.next) {
  47190. lastShape = lastShape.next;
  47191. }
  47192. return lastShape;
  47193. };
  47194. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47195. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  47196. };
  47197. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47198. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  47199. };
  47200. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47201. var v = impostor.physicsBody.linearVelocity;
  47202. if (!v)
  47203. return null;
  47204. return new BABYLON.Vector3(v.x, v.y, v.z);
  47205. };
  47206. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47207. var v = impostor.physicsBody.angularVelocity;
  47208. if (!v)
  47209. return null;
  47210. return new BABYLON.Vector3(v.x, v.y, v.z);
  47211. };
  47212. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47213. var staticBody = mass === 0;
  47214. //this will actually set the body's density and not its mass.
  47215. //But this is how oimo treats the mass variable.
  47216. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  47217. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  47218. };
  47219. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  47220. impostor.physicsBody.sleep();
  47221. };
  47222. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  47223. impostor.physicsBody.awake();
  47224. };
  47225. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47226. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  47227. if (minDistance !== void 0) {
  47228. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  47229. }
  47230. };
  47231. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47232. //TODO separate rotational and transational motors.
  47233. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47234. if (motor) {
  47235. motor.setMotor(speed, maxForce);
  47236. }
  47237. };
  47238. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  47239. //TODO separate rotational and transational motors.
  47240. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47241. if (motor) {
  47242. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  47243. }
  47244. };
  47245. OimoJSPlugin.prototype.dispose = function () {
  47246. this.world.clear();
  47247. };
  47248. return OimoJSPlugin;
  47249. })();
  47250. BABYLON.OimoJSPlugin = OimoJSPlugin;
  47251. })(BABYLON || (BABYLON = {}));
  47252. var BABYLON;
  47253. (function (BABYLON) {
  47254. var DisplayPassPostProcess = (function (_super) {
  47255. __extends(DisplayPassPostProcess, _super);
  47256. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47257. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  47258. }
  47259. return DisplayPassPostProcess;
  47260. })(BABYLON.PostProcess);
  47261. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47262. })(BABYLON || (BABYLON = {}));
  47263. var BABYLON;
  47264. (function (BABYLON) {
  47265. var SimplificationSettings = (function () {
  47266. function SimplificationSettings(quality, distance, optimizeMesh) {
  47267. this.quality = quality;
  47268. this.distance = distance;
  47269. this.optimizeMesh = optimizeMesh;
  47270. }
  47271. return SimplificationSettings;
  47272. })();
  47273. BABYLON.SimplificationSettings = SimplificationSettings;
  47274. var SimplificationQueue = (function () {
  47275. function SimplificationQueue() {
  47276. this.running = false;
  47277. this._simplificationArray = [];
  47278. }
  47279. SimplificationQueue.prototype.addTask = function (task) {
  47280. this._simplificationArray.push(task);
  47281. };
  47282. SimplificationQueue.prototype.executeNext = function () {
  47283. var task = this._simplificationArray.pop();
  47284. if (task) {
  47285. this.running = true;
  47286. this.runSimplification(task);
  47287. }
  47288. else {
  47289. this.running = false;
  47290. }
  47291. };
  47292. SimplificationQueue.prototype.runSimplification = function (task) {
  47293. var _this = this;
  47294. if (task.parallelProcessing) {
  47295. //parallel simplifier
  47296. task.settings.forEach(function (setting) {
  47297. var simplifier = _this.getSimplifier(task);
  47298. simplifier.simplify(setting, function (newMesh) {
  47299. task.mesh.addLODLevel(setting.distance, newMesh);
  47300. newMesh.isVisible = true;
  47301. //check if it is the last
  47302. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  47303. //all done, run the success callback.
  47304. task.successCallback();
  47305. }
  47306. _this.executeNext();
  47307. });
  47308. });
  47309. }
  47310. else {
  47311. //single simplifier.
  47312. var simplifier = this.getSimplifier(task);
  47313. var runDecimation = function (setting, callback) {
  47314. simplifier.simplify(setting, function (newMesh) {
  47315. task.mesh.addLODLevel(setting.distance, newMesh);
  47316. newMesh.isVisible = true;
  47317. //run the next quality level
  47318. callback();
  47319. });
  47320. };
  47321. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  47322. runDecimation(task.settings[loop.index], function () {
  47323. loop.executeNext();
  47324. });
  47325. }, function () {
  47326. //execution ended, run the success callback.
  47327. if (task.successCallback) {
  47328. task.successCallback();
  47329. }
  47330. _this.executeNext();
  47331. });
  47332. }
  47333. };
  47334. SimplificationQueue.prototype.getSimplifier = function (task) {
  47335. switch (task.simplificationType) {
  47336. case SimplificationType.QUADRATIC:
  47337. default:
  47338. return new QuadraticErrorSimplification(task.mesh);
  47339. }
  47340. };
  47341. return SimplificationQueue;
  47342. })();
  47343. BABYLON.SimplificationQueue = SimplificationQueue;
  47344. /**
  47345. * The implemented types of simplification.
  47346. * At the moment only Quadratic Error Decimation is implemented.
  47347. */
  47348. (function (SimplificationType) {
  47349. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  47350. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  47351. var SimplificationType = BABYLON.SimplificationType;
  47352. var DecimationTriangle = (function () {
  47353. function DecimationTriangle(vertices) {
  47354. this.vertices = vertices;
  47355. this.error = new Array(4);
  47356. this.deleted = false;
  47357. this.isDirty = false;
  47358. this.deletePending = false;
  47359. this.borderFactor = 0;
  47360. }
  47361. return DecimationTriangle;
  47362. })();
  47363. BABYLON.DecimationTriangle = DecimationTriangle;
  47364. var DecimationVertex = (function () {
  47365. function DecimationVertex(position, id) {
  47366. this.position = position;
  47367. this.id = id;
  47368. this.isBorder = true;
  47369. this.q = new QuadraticMatrix();
  47370. this.triangleCount = 0;
  47371. this.triangleStart = 0;
  47372. this.originalOffsets = [];
  47373. }
  47374. DecimationVertex.prototype.updatePosition = function (newPosition) {
  47375. this.position.copyFrom(newPosition);
  47376. };
  47377. return DecimationVertex;
  47378. })();
  47379. BABYLON.DecimationVertex = DecimationVertex;
  47380. var QuadraticMatrix = (function () {
  47381. function QuadraticMatrix(data) {
  47382. this.data = new Array(10);
  47383. for (var i = 0; i < 10; ++i) {
  47384. if (data && data[i]) {
  47385. this.data[i] = data[i];
  47386. }
  47387. else {
  47388. this.data[i] = 0;
  47389. }
  47390. }
  47391. }
  47392. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  47393. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  47394. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  47395. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  47396. return det;
  47397. };
  47398. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  47399. for (var i = 0; i < 10; ++i) {
  47400. this.data[i] += matrix.data[i];
  47401. }
  47402. };
  47403. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  47404. for (var i = 0; i < 10; ++i) {
  47405. this.data[i] += data[i];
  47406. }
  47407. };
  47408. QuadraticMatrix.prototype.add = function (matrix) {
  47409. var m = new QuadraticMatrix();
  47410. for (var i = 0; i < 10; ++i) {
  47411. m.data[i] = this.data[i] + matrix.data[i];
  47412. }
  47413. return m;
  47414. };
  47415. QuadraticMatrix.FromData = function (a, b, c, d) {
  47416. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  47417. };
  47418. //returning an array to avoid garbage collection
  47419. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  47420. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  47421. };
  47422. return QuadraticMatrix;
  47423. })();
  47424. BABYLON.QuadraticMatrix = QuadraticMatrix;
  47425. var Reference = (function () {
  47426. function Reference(vertexId, triangleId) {
  47427. this.vertexId = vertexId;
  47428. this.triangleId = triangleId;
  47429. }
  47430. return Reference;
  47431. })();
  47432. BABYLON.Reference = Reference;
  47433. /**
  47434. * An implementation of the Quadratic Error simplification algorithm.
  47435. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  47436. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  47437. * @author RaananW
  47438. */
  47439. var QuadraticErrorSimplification = (function () {
  47440. function QuadraticErrorSimplification(_mesh) {
  47441. this._mesh = _mesh;
  47442. this.initialized = false;
  47443. this.syncIterations = 5000;
  47444. this.aggressiveness = 7;
  47445. this.decimationIterations = 100;
  47446. this.boundingBoxEpsilon = BABYLON.Epsilon;
  47447. }
  47448. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  47449. var _this = this;
  47450. this.initDecimatedMesh();
  47451. //iterating through the submeshes array, one after the other.
  47452. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  47453. _this.initWithMesh(loop.index, function () {
  47454. _this.runDecimation(settings, loop.index, function () {
  47455. loop.executeNext();
  47456. });
  47457. }, settings.optimizeMesh);
  47458. }, function () {
  47459. setTimeout(function () {
  47460. successCallback(_this._reconstructedMesh);
  47461. }, 0);
  47462. });
  47463. };
  47464. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  47465. var _this = this;
  47466. var gCount = 0;
  47467. triangle.vertices.forEach(function (vertex) {
  47468. var count = 0;
  47469. var vPos = vertex.position;
  47470. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  47471. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  47472. ++count;
  47473. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  47474. ++count;
  47475. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  47476. ++count;
  47477. if (count > 1) {
  47478. ++gCount;
  47479. }
  47480. ;
  47481. });
  47482. if (gCount > 1) {
  47483. console.log(triangle, gCount);
  47484. }
  47485. return gCount > 1;
  47486. };
  47487. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  47488. var _this = this;
  47489. var targetCount = ~~(this.triangles.length * settings.quality);
  47490. var deletedTriangles = 0;
  47491. var triangleCount = this.triangles.length;
  47492. var iterationFunction = function (iteration, callback) {
  47493. setTimeout(function () {
  47494. if (iteration % 5 === 0) {
  47495. _this.updateMesh(iteration === 0);
  47496. }
  47497. for (var i = 0; i < _this.triangles.length; ++i) {
  47498. _this.triangles[i].isDirty = false;
  47499. }
  47500. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  47501. var trianglesIterator = function (i) {
  47502. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  47503. var t = _this.triangles[tIdx];
  47504. if (!t)
  47505. return;
  47506. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  47507. return;
  47508. }
  47509. for (var j = 0; j < 3; ++j) {
  47510. if (t.error[j] < threshold) {
  47511. var deleted0 = [];
  47512. var deleted1 = [];
  47513. var v0 = t.vertices[j];
  47514. var v1 = t.vertices[(j + 1) % 3];
  47515. if (v0.isBorder || v1.isBorder)
  47516. continue;
  47517. var p = BABYLON.Vector3.Zero();
  47518. var n = BABYLON.Vector3.Zero();
  47519. var uv = BABYLON.Vector2.Zero();
  47520. var color = new BABYLON.Color4(0, 0, 0, 1);
  47521. _this.calculateError(v0, v1, p, n, uv, color);
  47522. var delTr = [];
  47523. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  47524. continue;
  47525. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  47526. continue;
  47527. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  47528. continue;
  47529. var uniqueArray = [];
  47530. delTr.forEach(function (deletedT) {
  47531. if (uniqueArray.indexOf(deletedT) === -1) {
  47532. deletedT.deletePending = true;
  47533. uniqueArray.push(deletedT);
  47534. }
  47535. });
  47536. if (uniqueArray.length % 2 !== 0) {
  47537. continue;
  47538. }
  47539. v0.q = v1.q.add(v0.q);
  47540. v0.updatePosition(p);
  47541. var tStart = _this.references.length;
  47542. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  47543. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  47544. var tCount = _this.references.length - tStart;
  47545. if (tCount <= v0.triangleCount) {
  47546. if (tCount) {
  47547. for (var c = 0; c < tCount; c++) {
  47548. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  47549. }
  47550. }
  47551. }
  47552. else {
  47553. v0.triangleStart = tStart;
  47554. }
  47555. v0.triangleCount = tCount;
  47556. break;
  47557. }
  47558. }
  47559. };
  47560. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  47561. }, 0);
  47562. };
  47563. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  47564. if (triangleCount - deletedTriangles <= targetCount)
  47565. loop.breakLoop();
  47566. else {
  47567. iterationFunction(loop.index, function () {
  47568. loop.executeNext();
  47569. });
  47570. }
  47571. }, function () {
  47572. setTimeout(function () {
  47573. //reconstruct this part of the mesh
  47574. _this.reconstructMesh(submeshIndex);
  47575. successCallback();
  47576. }, 0);
  47577. });
  47578. };
  47579. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  47580. var _this = this;
  47581. this.vertices = [];
  47582. this.triangles = [];
  47583. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47584. var indices = this._mesh.getIndices();
  47585. var submesh = this._mesh.subMeshes[submeshIndex];
  47586. var findInVertices = function (positionToSearch) {
  47587. if (optimizeMesh) {
  47588. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  47589. if (_this.vertices[ii].position.equals(positionToSearch)) {
  47590. return _this.vertices[ii];
  47591. }
  47592. }
  47593. }
  47594. return null;
  47595. };
  47596. var vertexReferences = [];
  47597. var vertexInit = function (i) {
  47598. var offset = i + submesh.verticesStart;
  47599. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  47600. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  47601. vertex.originalOffsets.push(offset);
  47602. if (vertex.id === _this.vertices.length) {
  47603. _this.vertices.push(vertex);
  47604. }
  47605. vertexReferences.push(vertex.id);
  47606. };
  47607. //var totalVertices = mesh.getTotalVertices();
  47608. var totalVertices = submesh.verticesCount;
  47609. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  47610. var indicesInit = function (i) {
  47611. var offset = (submesh.indexStart / 3) + i;
  47612. var pos = (offset * 3);
  47613. var i0 = indices[pos + 0];
  47614. var i1 = indices[pos + 1];
  47615. var i2 = indices[pos + 2];
  47616. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  47617. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  47618. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  47619. var triangle = new DecimationTriangle([v0, v1, v2]);
  47620. triangle.originalOffset = pos;
  47621. _this.triangles.push(triangle);
  47622. };
  47623. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  47624. _this.init(callback);
  47625. });
  47626. });
  47627. };
  47628. QuadraticErrorSimplification.prototype.init = function (callback) {
  47629. var _this = this;
  47630. var triangleInit1 = function (i) {
  47631. var t = _this.triangles[i];
  47632. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  47633. for (var j = 0; j < 3; j++) {
  47634. 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))));
  47635. }
  47636. };
  47637. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  47638. var triangleInit2 = function (i) {
  47639. var t = _this.triangles[i];
  47640. for (var j = 0; j < 3; ++j) {
  47641. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  47642. }
  47643. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  47644. };
  47645. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  47646. _this.initialized = true;
  47647. callback();
  47648. });
  47649. });
  47650. };
  47651. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  47652. var newTriangles = [];
  47653. var i;
  47654. for (i = 0; i < this.vertices.length; ++i) {
  47655. this.vertices[i].triangleCount = 0;
  47656. }
  47657. var t;
  47658. var j;
  47659. for (i = 0; i < this.triangles.length; ++i) {
  47660. if (!this.triangles[i].deleted) {
  47661. t = this.triangles[i];
  47662. for (j = 0; j < 3; ++j) {
  47663. t.vertices[j].triangleCount = 1;
  47664. }
  47665. newTriangles.push(t);
  47666. }
  47667. }
  47668. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  47669. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  47670. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  47671. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  47672. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47673. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47674. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47675. var vertexCount = 0;
  47676. for (i = 0; i < this.vertices.length; ++i) {
  47677. var vertex = this.vertices[i];
  47678. vertex.id = vertexCount;
  47679. if (vertex.triangleCount) {
  47680. vertex.originalOffsets.forEach(function (originalOffset) {
  47681. newPositionData.push(vertex.position.x);
  47682. newPositionData.push(vertex.position.y);
  47683. newPositionData.push(vertex.position.z);
  47684. newNormalData.push(normalData[originalOffset * 3]);
  47685. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  47686. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  47687. if (uvs && uvs.length) {
  47688. newUVsData.push(uvs[(originalOffset * 2)]);
  47689. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  47690. }
  47691. else if (colorsData && colorsData.length) {
  47692. newColorsData.push(colorsData[(originalOffset * 4)]);
  47693. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  47694. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  47695. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  47696. }
  47697. ++vertexCount;
  47698. });
  47699. }
  47700. }
  47701. var startingIndex = this._reconstructedMesh.getTotalIndices();
  47702. var startingVertex = this._reconstructedMesh.getTotalVertices();
  47703. var submeshesArray = this._reconstructedMesh.subMeshes;
  47704. this._reconstructedMesh.subMeshes = [];
  47705. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  47706. var originalIndices = this._mesh.getIndices();
  47707. for (i = 0; i < newTriangles.length; ++i) {
  47708. t = newTriangles[i]; //now get the new referencing point for each vertex
  47709. [0, 1, 2].forEach(function (idx) {
  47710. var id = originalIndices[t.originalOffset + idx];
  47711. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  47712. if (offset < 0)
  47713. offset = 0;
  47714. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  47715. });
  47716. }
  47717. //overwriting the old vertex buffers and indices.
  47718. this._reconstructedMesh.setIndices(newIndicesArray);
  47719. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  47720. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  47721. if (newUVsData.length > 0)
  47722. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  47723. if (newColorsData.length > 0)
  47724. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  47725. //create submesh
  47726. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  47727. if (submeshIndex > 0) {
  47728. this._reconstructedMesh.subMeshes = [];
  47729. submeshesArray.forEach(function (submesh) {
  47730. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  47731. });
  47732. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  47733. }
  47734. };
  47735. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  47736. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  47737. this._reconstructedMesh.material = this._mesh.material;
  47738. this._reconstructedMesh.parent = this._mesh.parent;
  47739. this._reconstructedMesh.isVisible = false;
  47740. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  47741. };
  47742. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  47743. for (var i = 0; i < vertex1.triangleCount; ++i) {
  47744. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  47745. if (t.deleted)
  47746. continue;
  47747. var s = this.references[vertex1.triangleStart + i].vertexId;
  47748. var v1 = t.vertices[(s + 1) % 3];
  47749. var v2 = t.vertices[(s + 2) % 3];
  47750. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  47751. deletedArray[i] = true;
  47752. delTr.push(t);
  47753. continue;
  47754. }
  47755. var d1 = v1.position.subtract(point);
  47756. d1 = d1.normalize();
  47757. var d2 = v2.position.subtract(point);
  47758. d2 = d2.normalize();
  47759. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  47760. return true;
  47761. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  47762. deletedArray[i] = false;
  47763. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  47764. return true;
  47765. }
  47766. return false;
  47767. };
  47768. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  47769. var newDeleted = deletedTriangles;
  47770. for (var i = 0; i < vertex.triangleCount; ++i) {
  47771. var ref = this.references[vertex.triangleStart + i];
  47772. var t = this.triangles[ref.triangleId];
  47773. if (t.deleted)
  47774. continue;
  47775. if (deletedArray[i] && t.deletePending) {
  47776. t.deleted = true;
  47777. newDeleted++;
  47778. continue;
  47779. }
  47780. t.vertices[ref.vertexId] = origVertex;
  47781. t.isDirty = true;
  47782. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  47783. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  47784. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  47785. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  47786. this.references.push(ref);
  47787. }
  47788. return newDeleted;
  47789. };
  47790. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  47791. for (var i = 0; i < this.vertices.length; ++i) {
  47792. var vCount = [];
  47793. var vId = [];
  47794. var v = this.vertices[i];
  47795. var j;
  47796. for (j = 0; j < v.triangleCount; ++j) {
  47797. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  47798. for (var ii = 0; ii < 3; ii++) {
  47799. var ofs = 0;
  47800. var vv = triangle.vertices[ii];
  47801. while (ofs < vCount.length) {
  47802. if (vId[ofs] === vv.id)
  47803. break;
  47804. ++ofs;
  47805. }
  47806. if (ofs === vCount.length) {
  47807. vCount.push(1);
  47808. vId.push(vv.id);
  47809. }
  47810. else {
  47811. vCount[ofs]++;
  47812. }
  47813. }
  47814. }
  47815. for (j = 0; j < vCount.length; ++j) {
  47816. if (vCount[j] === 1) {
  47817. this.vertices[vId[j]].isBorder = true;
  47818. }
  47819. else {
  47820. this.vertices[vId[j]].isBorder = false;
  47821. }
  47822. }
  47823. }
  47824. };
  47825. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  47826. if (identifyBorders === void 0) { identifyBorders = false; }
  47827. var i;
  47828. if (!identifyBorders) {
  47829. var newTrianglesVector = [];
  47830. for (i = 0; i < this.triangles.length; ++i) {
  47831. if (!this.triangles[i].deleted) {
  47832. newTrianglesVector.push(this.triangles[i]);
  47833. }
  47834. }
  47835. this.triangles = newTrianglesVector;
  47836. }
  47837. for (i = 0; i < this.vertices.length; ++i) {
  47838. this.vertices[i].triangleCount = 0;
  47839. this.vertices[i].triangleStart = 0;
  47840. }
  47841. var t;
  47842. var j;
  47843. var v;
  47844. for (i = 0; i < this.triangles.length; ++i) {
  47845. t = this.triangles[i];
  47846. for (j = 0; j < 3; ++j) {
  47847. v = t.vertices[j];
  47848. v.triangleCount++;
  47849. }
  47850. }
  47851. var tStart = 0;
  47852. for (i = 0; i < this.vertices.length; ++i) {
  47853. this.vertices[i].triangleStart = tStart;
  47854. tStart += this.vertices[i].triangleCount;
  47855. this.vertices[i].triangleCount = 0;
  47856. }
  47857. var newReferences = new Array(this.triangles.length * 3);
  47858. for (i = 0; i < this.triangles.length; ++i) {
  47859. t = this.triangles[i];
  47860. for (j = 0; j < 3; ++j) {
  47861. v = t.vertices[j];
  47862. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  47863. v.triangleCount++;
  47864. }
  47865. }
  47866. this.references = newReferences;
  47867. if (identifyBorders) {
  47868. this.identifyBorder();
  47869. }
  47870. };
  47871. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  47872. var x = point.x;
  47873. var y = point.y;
  47874. var z = point.z;
  47875. 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
  47876. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  47877. };
  47878. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  47879. var q = vertex1.q.add(vertex2.q);
  47880. var border = vertex1.isBorder && vertex2.isBorder;
  47881. var error = 0;
  47882. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  47883. if (qDet !== 0 && !border) {
  47884. if (!pointResult) {
  47885. pointResult = BABYLON.Vector3.Zero();
  47886. }
  47887. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  47888. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  47889. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  47890. error = this.vertexError(q, pointResult);
  47891. }
  47892. else {
  47893. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  47894. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  47895. var error1 = this.vertexError(q, vertex1.position);
  47896. var error2 = this.vertexError(q, vertex2.position);
  47897. var error3 = this.vertexError(q, p3);
  47898. error = Math.min(error1, error2, error3);
  47899. if (error === error1) {
  47900. if (pointResult) {
  47901. pointResult.copyFrom(vertex1.position);
  47902. }
  47903. }
  47904. else if (error === error2) {
  47905. if (pointResult) {
  47906. pointResult.copyFrom(vertex2.position);
  47907. }
  47908. }
  47909. else {
  47910. if (pointResult) {
  47911. pointResult.copyFrom(p3);
  47912. }
  47913. }
  47914. }
  47915. return error;
  47916. };
  47917. return QuadraticErrorSimplification;
  47918. })();
  47919. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  47920. })(BABYLON || (BABYLON = {}));
  47921. var BABYLON;
  47922. (function (BABYLON) {
  47923. var serializedGeometries = [];
  47924. var serializeGeometry = function (geometry, serializationGeometries) {
  47925. if (serializedGeometries[geometry.id]) {
  47926. return;
  47927. }
  47928. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  47929. serializationGeometries.boxes.push(geometry.serialize());
  47930. }
  47931. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  47932. serializationGeometries.spheres.push(geometry.serialize());
  47933. }
  47934. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  47935. serializationGeometries.cylinders.push(geometry.serialize());
  47936. }
  47937. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  47938. serializationGeometries.toruses.push(geometry.serialize());
  47939. }
  47940. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  47941. serializationGeometries.grounds.push(geometry.serialize());
  47942. }
  47943. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  47944. serializationGeometries.planes.push(geometry.serialize());
  47945. }
  47946. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  47947. serializationGeometries.torusKnots.push(geometry.serialize());
  47948. }
  47949. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  47950. throw new Error("Unknown primitive type");
  47951. }
  47952. else {
  47953. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  47954. }
  47955. serializedGeometries[geometry.id] = true;
  47956. };
  47957. var serializeMesh = function (mesh, serializationScene) {
  47958. var serializationObject = {};
  47959. serializationObject.name = mesh.name;
  47960. serializationObject.id = mesh.id;
  47961. if (BABYLON.Tags.HasTags(mesh)) {
  47962. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  47963. }
  47964. serializationObject.position = mesh.position.asArray();
  47965. if (mesh.rotationQuaternion) {
  47966. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  47967. }
  47968. else if (mesh.rotation) {
  47969. serializationObject.rotation = mesh.rotation.asArray();
  47970. }
  47971. serializationObject.scaling = mesh.scaling.asArray();
  47972. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  47973. serializationObject.isEnabled = mesh.isEnabled();
  47974. serializationObject.isVisible = mesh.isVisible;
  47975. serializationObject.infiniteDistance = mesh.infiniteDistance;
  47976. serializationObject.pickable = mesh.isPickable;
  47977. serializationObject.receiveShadows = mesh.receiveShadows;
  47978. serializationObject.billboardMode = mesh.billboardMode;
  47979. serializationObject.visibility = mesh.visibility;
  47980. serializationObject.checkCollisions = mesh.checkCollisions;
  47981. // Parent
  47982. if (mesh.parent) {
  47983. serializationObject.parentId = mesh.parent.id;
  47984. }
  47985. // Geometry
  47986. var geometry = mesh._geometry;
  47987. if (geometry) {
  47988. var geometryId = geometry.id;
  47989. serializationObject.geometryId = geometryId;
  47990. if (!mesh.getScene().getGeometryByID(geometryId)) {
  47991. // 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
  47992. serializeGeometry(geometry, serializationScene.geometries);
  47993. }
  47994. // SubMeshes
  47995. serializationObject.subMeshes = [];
  47996. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  47997. var subMesh = mesh.subMeshes[subIndex];
  47998. serializationObject.subMeshes.push({
  47999. materialIndex: subMesh.materialIndex,
  48000. verticesStart: subMesh.verticesStart,
  48001. verticesCount: subMesh.verticesCount,
  48002. indexStart: subMesh.indexStart,
  48003. indexCount: subMesh.indexCount
  48004. });
  48005. }
  48006. }
  48007. // Material
  48008. if (mesh.material) {
  48009. serializationObject.materialId = mesh.material.id;
  48010. }
  48011. else {
  48012. mesh.material = null;
  48013. }
  48014. // Skeleton
  48015. if (mesh.skeleton) {
  48016. serializationObject.skeletonId = mesh.skeleton.id;
  48017. }
  48018. // Physics
  48019. //TODO implement correct serialization for physics impostors.
  48020. if (mesh.getPhysicsImpostor()) {
  48021. serializationObject.physicsMass = mesh.getPhysicsMass();
  48022. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  48023. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  48024. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  48025. }
  48026. // Instances
  48027. serializationObject.instances = [];
  48028. for (var index = 0; index < mesh.instances.length; index++) {
  48029. var instance = mesh.instances[index];
  48030. var serializationInstance = {
  48031. name: instance.name,
  48032. position: instance.position.asArray(),
  48033. scaling: instance.scaling.asArray()
  48034. };
  48035. if (instance.rotationQuaternion) {
  48036. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  48037. }
  48038. else if (instance.rotation) {
  48039. serializationInstance.rotation = instance.rotation.asArray();
  48040. }
  48041. serializationObject.instances.push(serializationInstance);
  48042. // Animations
  48043. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  48044. serializationInstance.ranges = instance.serializeAnimationRanges();
  48045. }
  48046. // Animations
  48047. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  48048. serializationObject.ranges = mesh.serializeAnimationRanges();
  48049. // Layer mask
  48050. serializationObject.layerMask = mesh.layerMask;
  48051. // Action Manager
  48052. if (mesh.actionManager) {
  48053. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  48054. }
  48055. return serializationObject;
  48056. };
  48057. var finalizeSingleMesh = function (mesh, serializationObject) {
  48058. //only works if the mesh is already loaded
  48059. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48060. //serialize material
  48061. if (mesh.material) {
  48062. if (mesh.material instanceof BABYLON.StandardMaterial) {
  48063. serializationObject.materials = serializationObject.materials || [];
  48064. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48065. serializationObject.materials.push(mesh.material.serialize());
  48066. }
  48067. }
  48068. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  48069. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  48070. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48071. serializationObject.multiMaterials.push(mesh.material.serialize());
  48072. }
  48073. }
  48074. }
  48075. //serialize geometry
  48076. var geometry = mesh._geometry;
  48077. if (geometry) {
  48078. if (!serializationObject.geometries) {
  48079. serializationObject.geometries = {};
  48080. serializationObject.geometries.boxes = [];
  48081. serializationObject.geometries.spheres = [];
  48082. serializationObject.geometries.cylinders = [];
  48083. serializationObject.geometries.toruses = [];
  48084. serializationObject.geometries.grounds = [];
  48085. serializationObject.geometries.planes = [];
  48086. serializationObject.geometries.torusKnots = [];
  48087. serializationObject.geometries.vertexData = [];
  48088. }
  48089. serializeGeometry(geometry, serializationObject.geometries);
  48090. }
  48091. // Skeletons
  48092. if (mesh.skeleton) {
  48093. serializationObject.skeletons = serializationObject.skeletons || [];
  48094. serializationObject.skeletons.push(mesh.skeleton.serialize());
  48095. }
  48096. //serialize the actual mesh
  48097. serializationObject.meshes = serializationObject.meshes || [];
  48098. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48099. }
  48100. };
  48101. var SceneSerializer = (function () {
  48102. function SceneSerializer() {
  48103. }
  48104. SceneSerializer.ClearCache = function () {
  48105. serializedGeometries = [];
  48106. };
  48107. SceneSerializer.Serialize = function (scene) {
  48108. var serializationObject = {};
  48109. // Scene
  48110. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  48111. serializationObject.autoClear = scene.autoClear;
  48112. serializationObject.clearColor = scene.clearColor.asArray();
  48113. serializationObject.ambientColor = scene.ambientColor.asArray();
  48114. serializationObject.gravity = scene.gravity.asArray();
  48115. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  48116. serializationObject.workerCollisions = scene.workerCollisions;
  48117. // Fog
  48118. if (scene.fogMode && scene.fogMode !== 0) {
  48119. serializationObject.fogMode = scene.fogMode;
  48120. serializationObject.fogColor = scene.fogColor.asArray();
  48121. serializationObject.fogStart = scene.fogStart;
  48122. serializationObject.fogEnd = scene.fogEnd;
  48123. serializationObject.fogDensity = scene.fogDensity;
  48124. }
  48125. //Physics
  48126. if (scene.isPhysicsEnabled()) {
  48127. serializationObject.physicsEnabled = true;
  48128. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  48129. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  48130. }
  48131. // Lights
  48132. serializationObject.lights = [];
  48133. var index;
  48134. var light;
  48135. for (index = 0; index < scene.lights.length; index++) {
  48136. light = scene.lights[index];
  48137. serializationObject.lights.push(light.serialize());
  48138. }
  48139. // Cameras
  48140. serializationObject.cameras = [];
  48141. for (index = 0; index < scene.cameras.length; index++) {
  48142. var camera = scene.cameras[index];
  48143. serializationObject.cameras.push(camera.serialize());
  48144. }
  48145. if (scene.activeCamera) {
  48146. serializationObject.activeCameraID = scene.activeCamera.id;
  48147. }
  48148. // Animations
  48149. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  48150. // Materials
  48151. serializationObject.materials = [];
  48152. serializationObject.multiMaterials = [];
  48153. var material;
  48154. for (index = 0; index < scene.materials.length; index++) {
  48155. material = scene.materials[index];
  48156. serializationObject.materials.push(material.serialize());
  48157. }
  48158. // MultiMaterials
  48159. serializationObject.multiMaterials = [];
  48160. for (index = 0; index < scene.multiMaterials.length; index++) {
  48161. var multiMaterial = scene.multiMaterials[index];
  48162. serializationObject.multiMaterials.push(multiMaterial.serialize());
  48163. }
  48164. // Skeletons
  48165. serializationObject.skeletons = [];
  48166. for (index = 0; index < scene.skeletons.length; index++) {
  48167. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  48168. }
  48169. // Geometries
  48170. serializationObject.geometries = {};
  48171. serializationObject.geometries.boxes = [];
  48172. serializationObject.geometries.spheres = [];
  48173. serializationObject.geometries.cylinders = [];
  48174. serializationObject.geometries.toruses = [];
  48175. serializationObject.geometries.grounds = [];
  48176. serializationObject.geometries.planes = [];
  48177. serializationObject.geometries.torusKnots = [];
  48178. serializationObject.geometries.vertexData = [];
  48179. serializedGeometries = [];
  48180. var geometries = scene.getGeometries();
  48181. for (index = 0; index < geometries.length; index++) {
  48182. var geometry = geometries[index];
  48183. if (geometry.isReady()) {
  48184. serializeGeometry(geometry, serializationObject.geometries);
  48185. }
  48186. }
  48187. // Meshes
  48188. serializationObject.meshes = [];
  48189. for (index = 0; index < scene.meshes.length; index++) {
  48190. var abstractMesh = scene.meshes[index];
  48191. if (abstractMesh instanceof BABYLON.Mesh) {
  48192. var mesh = abstractMesh;
  48193. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48194. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48195. }
  48196. }
  48197. }
  48198. // Particles Systems
  48199. serializationObject.particleSystems = [];
  48200. for (index = 0; index < scene.particleSystems.length; index++) {
  48201. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  48202. }
  48203. // Lens flares
  48204. serializationObject.lensFlareSystems = [];
  48205. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  48206. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  48207. }
  48208. // Shadows
  48209. serializationObject.shadowGenerators = [];
  48210. for (index = 0; index < scene.lights.length; index++) {
  48211. light = scene.lights[index];
  48212. if (light.getShadowGenerator()) {
  48213. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  48214. }
  48215. }
  48216. // Action Manager
  48217. if (scene.actionManager) {
  48218. serializationObject.actions = scene.actionManager.serialize("scene");
  48219. }
  48220. return serializationObject;
  48221. };
  48222. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  48223. if (withParents === void 0) { withParents = false; }
  48224. if (withChildren === void 0) { withChildren = false; }
  48225. var serializationObject = {};
  48226. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  48227. if (withParents || withChildren) {
  48228. //deliberate for loop! not for each, appended should be processed as well.
  48229. for (var i = 0; i < toSerialize.length; ++i) {
  48230. if (withChildren) {
  48231. toSerialize[i].getDescendants().forEach(function (node) {
  48232. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  48233. toSerialize.push(node);
  48234. }
  48235. });
  48236. }
  48237. //make sure the array doesn't contain the object already
  48238. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  48239. toSerialize.push(toSerialize[i].parent);
  48240. }
  48241. }
  48242. }
  48243. toSerialize.forEach(function (mesh) {
  48244. finalizeSingleMesh(mesh, serializationObject);
  48245. });
  48246. return serializationObject;
  48247. };
  48248. return SceneSerializer;
  48249. })();
  48250. BABYLON.SceneSerializer = SceneSerializer;
  48251. })(BABYLON || (BABYLON = {}));
  48252. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  48253. // Huge respect for a such great lib.
  48254. // Earcut license:
  48255. // Copyright (c) 2016, Mapbox
  48256. //
  48257. // Permission to use, copy, modify, and/or distribute this software for any purpose
  48258. // with or without fee is hereby granted, provided that the above copyright notice
  48259. // and this permission notice appear in all copies.
  48260. //
  48261. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  48262. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  48263. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  48264. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  48265. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  48266. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  48267. // THIS SOFTWARE.
  48268. var Earcut;
  48269. (function (Earcut) {
  48270. /**
  48271. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  48272. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  48273. * @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).
  48274. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  48275. */
  48276. function earcut(data, holeIndices, dim) {
  48277. dim = dim || 2;
  48278. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  48279. if (!outerNode)
  48280. return triangles;
  48281. var minX, minY, maxX, maxY, x, y, size;
  48282. if (hasHoles)
  48283. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  48284. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  48285. if (data.length > 80 * dim) {
  48286. minX = maxX = data[0];
  48287. minY = maxY = data[1];
  48288. for (var i = dim; i < outerLen; i += dim) {
  48289. x = data[i];
  48290. y = data[i + 1];
  48291. if (x < minX)
  48292. minX = x;
  48293. if (y < minY)
  48294. minY = y;
  48295. if (x > maxX)
  48296. maxX = x;
  48297. if (y > maxY)
  48298. maxY = y;
  48299. }
  48300. // minX, minY and size are later used to transform coords into integers for z-order calculation
  48301. size = Math.max(maxX - minX, maxY - minY);
  48302. }
  48303. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  48304. return triangles;
  48305. }
  48306. Earcut.earcut = earcut;
  48307. // create a circular doubly linked list from polygon points in the specified winding order
  48308. function linkedList(data, start, end, dim, clockwise) {
  48309. var i, last;
  48310. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  48311. for (i = start; i < end; i += dim)
  48312. last = insertNode(i, data[i], data[i + 1], last);
  48313. }
  48314. else {
  48315. for (i = end - dim; i >= start; i -= dim)
  48316. last = insertNode(i, data[i], data[i + 1], last);
  48317. }
  48318. if (last && equals(last, last.next)) {
  48319. removeNode(last);
  48320. last = last.next;
  48321. }
  48322. return last;
  48323. }
  48324. // eliminate colinear or duplicate points
  48325. function filterPoints(start, end) {
  48326. if (!start)
  48327. return start;
  48328. if (!end)
  48329. end = start;
  48330. var p = start, again;
  48331. do {
  48332. again = false;
  48333. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  48334. removeNode(p);
  48335. p = end = p.prev;
  48336. if (p === p.next)
  48337. return null;
  48338. again = true;
  48339. }
  48340. else {
  48341. p = p.next;
  48342. }
  48343. } while (again || p !== end);
  48344. return end;
  48345. }
  48346. // main ear slicing loop which triangulates a polygon (given as a linked list)
  48347. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  48348. if (!ear)
  48349. return;
  48350. // interlink polygon nodes in z-order
  48351. if (!pass && size)
  48352. indexCurve(ear, minX, minY, size);
  48353. var stop = ear, prev, next;
  48354. // iterate through ears, slicing them one by one
  48355. while (ear.prev !== ear.next) {
  48356. prev = ear.prev;
  48357. next = ear.next;
  48358. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  48359. // cut off the triangle
  48360. triangles.push(prev.i / dim);
  48361. triangles.push(ear.i / dim);
  48362. triangles.push(next.i / dim);
  48363. removeNode(ear);
  48364. // skipping the next vertice leads to less sliver triangles
  48365. ear = next.next;
  48366. stop = next.next;
  48367. continue;
  48368. }
  48369. ear = next;
  48370. // if we looped through the whole remaining polygon and can't find any more ears
  48371. if (ear === stop) {
  48372. // try filtering points and slicing again
  48373. if (!pass) {
  48374. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  48375. }
  48376. else if (pass === 1) {
  48377. ear = cureLocalIntersections(ear, triangles, dim);
  48378. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  48379. }
  48380. else if (pass === 2) {
  48381. splitEarcut(ear, triangles, dim, minX, minY, size);
  48382. }
  48383. break;
  48384. }
  48385. }
  48386. }
  48387. // check whether a polygon node forms a valid ear with adjacent nodes
  48388. function isEar(ear) {
  48389. var a = ear.prev, b = ear, c = ear.next;
  48390. if (area(a, b, c) >= 0)
  48391. return false; // reflex, can't be an ear
  48392. // now make sure we don't have other points inside the potential ear
  48393. var p = ear.next.next;
  48394. while (p !== ear.prev) {
  48395. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48396. area(p.prev, p, p.next) >= 0)
  48397. return false;
  48398. p = p.next;
  48399. }
  48400. return true;
  48401. }
  48402. function isEarHashed(ear, minX, minY, size) {
  48403. var a = ear.prev, b = ear, c = ear.next;
  48404. if (area(a, b, c) >= 0)
  48405. return false; // reflex, can't be an ear
  48406. // triangle bbox; min & max are calculated like this for speed
  48407. 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);
  48408. // z-order range for the current triangle bbox;
  48409. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  48410. // first look for points inside the triangle in increasing z-order
  48411. var p = ear.nextZ;
  48412. while (p && p.z <= maxZ) {
  48413. if (p !== ear.prev &&
  48414. p !== ear.next &&
  48415. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48416. area(p.prev, p, p.next) >= 0)
  48417. return false;
  48418. p = p.nextZ;
  48419. }
  48420. // then look for points in decreasing z-order
  48421. p = ear.prevZ;
  48422. while (p && p.z >= minZ) {
  48423. if (p !== ear.prev &&
  48424. p !== ear.next &&
  48425. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48426. area(p.prev, p, p.next) >= 0)
  48427. return false;
  48428. p = p.prevZ;
  48429. }
  48430. return true;
  48431. }
  48432. // go through all polygon nodes and cure small local self-intersections
  48433. function cureLocalIntersections(start, triangles, dim) {
  48434. var p = start;
  48435. do {
  48436. var a = p.prev, b = p.next.next;
  48437. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  48438. triangles.push(a.i / dim);
  48439. triangles.push(p.i / dim);
  48440. triangles.push(b.i / dim);
  48441. // remove two nodes involved
  48442. removeNode(p);
  48443. removeNode(p.next);
  48444. p = start = b;
  48445. }
  48446. p = p.next;
  48447. } while (p !== start);
  48448. return p;
  48449. }
  48450. // try splitting polygon into two and triangulate them independently
  48451. function splitEarcut(start, triangles, dim, minX, minY, size) {
  48452. // look for a valid diagonal that divides the polygon into two
  48453. var a = start;
  48454. do {
  48455. var b = a.next.next;
  48456. while (b !== a.prev) {
  48457. if (a.i !== b.i && isValidDiagonal(a, b)) {
  48458. // split the polygon in two by the diagonal
  48459. var c = splitPolygon(a, b);
  48460. // filter colinear points around the cuts
  48461. a = filterPoints(a, a.next);
  48462. c = filterPoints(c, c.next);
  48463. // run earcut on each half
  48464. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  48465. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  48466. return;
  48467. }
  48468. b = b.next;
  48469. }
  48470. a = a.next;
  48471. } while (a !== start);
  48472. }
  48473. // link every hole into the outer loop, producing a single-ring polygon without holes
  48474. function eliminateHoles(data, holeIndices, outerNode, dim) {
  48475. var queue = [], i, len, start, end, list;
  48476. for (i = 0, len = holeIndices.length; i < len; i++) {
  48477. start = holeIndices[i] * dim;
  48478. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48479. list = linkedList(data, start, end, dim, false);
  48480. if (list === list.next)
  48481. list.steiner = true;
  48482. queue.push(getLeftmost(list));
  48483. }
  48484. queue.sort(compareX);
  48485. // process holes from left to right
  48486. for (i = 0; i < queue.length; i++) {
  48487. eliminateHole(queue[i], outerNode);
  48488. outerNode = filterPoints(outerNode, outerNode.next);
  48489. }
  48490. return outerNode;
  48491. }
  48492. function compareX(a, b) {
  48493. return a.x - b.x;
  48494. }
  48495. // find a bridge between vertices that connects hole with an outer ring and and link it
  48496. function eliminateHole(hole, outerNode) {
  48497. outerNode = findHoleBridge(hole, outerNode);
  48498. if (outerNode) {
  48499. var b = splitPolygon(outerNode, hole);
  48500. filterPoints(b, b.next);
  48501. }
  48502. }
  48503. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  48504. function findHoleBridge(hole, outerNode) {
  48505. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  48506. // find a segment intersected by a ray from the hole's leftmost point to the left;
  48507. // segment's endpoint with lesser x will be potential connection point
  48508. do {
  48509. if (hy <= p.y && hy >= p.next.y) {
  48510. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  48511. if (x <= hx && x > qx) {
  48512. qx = x;
  48513. if (x === hx) {
  48514. if (hy === p.y)
  48515. return p;
  48516. if (hy === p.next.y)
  48517. return p.next;
  48518. }
  48519. m = p.x < p.next.x ? p : p.next;
  48520. }
  48521. }
  48522. p = p.next;
  48523. } while (p !== outerNode);
  48524. if (!m)
  48525. return null;
  48526. if (hx === qx)
  48527. return m.prev; // hole touches outer segment; pick lower endpoint
  48528. // look for points inside the triangle of hole point, segment intersection and endpoint;
  48529. // if there are no points found, we have a valid connection;
  48530. // otherwise choose the point of the minimum angle with the ray as connection point
  48531. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  48532. p = m.next;
  48533. while (p !== stop) {
  48534. if (hx >= p.x &&
  48535. p.x >= mx &&
  48536. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  48537. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  48538. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  48539. m = p;
  48540. tanMin = tan;
  48541. }
  48542. }
  48543. p = p.next;
  48544. }
  48545. return m;
  48546. }
  48547. // interlink polygon nodes in z-order
  48548. function indexCurve(start, minX, minY, size) {
  48549. var p = start;
  48550. do {
  48551. if (p.z === null)
  48552. p.z = zOrder(p.x, p.y, minX, minY, size);
  48553. p.prevZ = p.prev;
  48554. p.nextZ = p.next;
  48555. p = p.next;
  48556. } while (p !== start);
  48557. p.prevZ.nextZ = null;
  48558. p.prevZ = null;
  48559. sortLinked(p);
  48560. }
  48561. // Simon Tatham's linked list merge sort algorithm
  48562. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  48563. function sortLinked(list) {
  48564. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  48565. do {
  48566. p = list;
  48567. list = null;
  48568. tail = null;
  48569. numMerges = 0;
  48570. while (p) {
  48571. numMerges++;
  48572. q = p;
  48573. pSize = 0;
  48574. for (i = 0; i < inSize; i++) {
  48575. pSize++;
  48576. q = q.nextZ;
  48577. if (!q)
  48578. break;
  48579. }
  48580. qSize = inSize;
  48581. while (pSize > 0 || (qSize > 0 && q)) {
  48582. if (pSize === 0) {
  48583. e = q;
  48584. q = q.nextZ;
  48585. qSize--;
  48586. }
  48587. else if (qSize === 0 || !q) {
  48588. e = p;
  48589. p = p.nextZ;
  48590. pSize--;
  48591. }
  48592. else if (p.z <= q.z) {
  48593. e = p;
  48594. p = p.nextZ;
  48595. pSize--;
  48596. }
  48597. else {
  48598. e = q;
  48599. q = q.nextZ;
  48600. qSize--;
  48601. }
  48602. if (tail)
  48603. tail.nextZ = e;
  48604. else
  48605. list = e;
  48606. e.prevZ = tail;
  48607. tail = e;
  48608. }
  48609. p = q;
  48610. }
  48611. tail.nextZ = null;
  48612. inSize *= 2;
  48613. } while (numMerges > 1);
  48614. return list;
  48615. }
  48616. // z-order of a point given coords and size of the data bounding box
  48617. function zOrder(x, y, minX, minY, size) {
  48618. // coords are transformed into non-negative 15-bit integer range
  48619. x = 32767 * (x - minX) / size;
  48620. y = 32767 * (y - minY) / size;
  48621. x = (x | (x << 8)) & 0x00FF00FF;
  48622. x = (x | (x << 4)) & 0x0F0F0F0F;
  48623. x = (x | (x << 2)) & 0x33333333;
  48624. x = (x | (x << 1)) & 0x55555555;
  48625. y = (y | (y << 8)) & 0x00FF00FF;
  48626. y = (y | (y << 4)) & 0x0F0F0F0F;
  48627. y = (y | (y << 2)) & 0x33333333;
  48628. y = (y | (y << 1)) & 0x55555555;
  48629. return x | (y << 1);
  48630. }
  48631. // find the leftmost node of a polygon ring
  48632. function getLeftmost(start) {
  48633. var p = start, leftmost = start;
  48634. do {
  48635. if (p.x < leftmost.x)
  48636. leftmost = p;
  48637. p = p.next;
  48638. } while (p !== start);
  48639. return leftmost;
  48640. }
  48641. // check if a point lies within a convex triangle
  48642. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  48643. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  48644. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  48645. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  48646. }
  48647. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  48648. function isValidDiagonal(a, b) {
  48649. return a.next.i !== b.i &&
  48650. a.prev.i !== b.i &&
  48651. !intersectsPolygon(a, b) &&
  48652. locallyInside(a, b) &&
  48653. locallyInside(b, a) &&
  48654. middleInside(a, b);
  48655. }
  48656. // signed area of a triangle
  48657. function area(p, q, r) {
  48658. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  48659. }
  48660. // check if two points are equal
  48661. function equals(p1, p2) {
  48662. return p1.x === p2.x && p1.y === p2.y;
  48663. }
  48664. // check if two segments intersect
  48665. function intersects(p1, q1, p2, q2) {
  48666. if ((equals(p1, q1) && equals(p2, q2)) ||
  48667. (equals(p1, q2) && equals(p2, q1)))
  48668. return true;
  48669. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  48670. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  48671. }
  48672. // check if a polygon diagonal intersects any polygon segments
  48673. function intersectsPolygon(a, b) {
  48674. var p = a;
  48675. do {
  48676. if (p.i !== a.i &&
  48677. p.next.i !== a.i &&
  48678. p.i !== b.i &&
  48679. p.next.i !== b.i &&
  48680. intersects(p, p.next, a, b))
  48681. return true;
  48682. p = p.next;
  48683. } while (p !== a);
  48684. return false;
  48685. }
  48686. // check if a polygon diagonal is locally inside the polygon
  48687. function locallyInside(a, b) {
  48688. return area(a.prev, a, a.next) < 0
  48689. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  48690. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  48691. }
  48692. // check if the middle point of a polygon diagonal is inside the polygon
  48693. function middleInside(a, b) {
  48694. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  48695. do {
  48696. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  48697. inside = !inside;
  48698. p = p.next;
  48699. } while (p !== a);
  48700. return inside;
  48701. }
  48702. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  48703. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  48704. function splitPolygon(a, b) {
  48705. 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;
  48706. a.next = b;
  48707. b.prev = a;
  48708. a2.next = an;
  48709. an.prev = a2;
  48710. b2.next = a2;
  48711. a2.prev = b2;
  48712. bp.next = b2;
  48713. b2.prev = bp;
  48714. return b2;
  48715. }
  48716. // create a node and optionally link it with previous one (in a circular doubly linked list)
  48717. function insertNode(i, x, y, last) {
  48718. var p = new Node(i, x, y);
  48719. if (!last) {
  48720. p.prev = p;
  48721. p.next = p;
  48722. }
  48723. else {
  48724. p.next = last.next;
  48725. p.prev = last;
  48726. last.next.prev = p;
  48727. last.next = p;
  48728. }
  48729. return p;
  48730. }
  48731. function removeNode(p) {
  48732. p.next.prev = p.prev;
  48733. p.prev.next = p.next;
  48734. if (p.prevZ)
  48735. p.prevZ.nextZ = p.nextZ;
  48736. if (p.nextZ)
  48737. p.nextZ.prevZ = p.prevZ;
  48738. }
  48739. function Node(i, x, y) {
  48740. // vertice index in coordinates array
  48741. this.i = i;
  48742. // vertex coordinates
  48743. this.x = x;
  48744. this.y = y;
  48745. // previous and next vertice nodes in a polygon ring
  48746. this.prev = null;
  48747. this.next = null;
  48748. // z-order curve value
  48749. this.z = null;
  48750. // previous and next nodes in z-order
  48751. this.prevZ = null;
  48752. this.nextZ = null;
  48753. // indicates whether this is a steiner point
  48754. this.steiner = false;
  48755. }
  48756. /**
  48757. * return a percentage difference between the polygon area and its triangulation area;
  48758. * used to verify correctness of triangulation
  48759. */
  48760. function deviation(data, holeIndices, dim, triangles) {
  48761. var hasHoles = holeIndices && holeIndices.length;
  48762. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  48763. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  48764. if (hasHoles) {
  48765. for (var i = 0, len = holeIndices.length; i < len; i++) {
  48766. var start = holeIndices[i] * dim;
  48767. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  48768. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  48769. }
  48770. }
  48771. var trianglesArea = 0;
  48772. for (i = 0; i < triangles.length; i += 3) {
  48773. var a = triangles[i] * dim;
  48774. var b = triangles[i + 1] * dim;
  48775. var c = triangles[i + 2] * dim;
  48776. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  48777. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  48778. }
  48779. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  48780. }
  48781. Earcut.deviation = deviation;
  48782. ;
  48783. function signedArea(data, start, end, dim) {
  48784. var sum = 0;
  48785. for (var i = start, j = end - dim; i < end; i += dim) {
  48786. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  48787. j = i;
  48788. }
  48789. return sum;
  48790. }
  48791. /**
  48792. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  48793. */
  48794. function flatten(data) {
  48795. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  48796. for (var i = 0; i < data.length; i++) {
  48797. for (var j = 0; j < data[i].length; j++) {
  48798. for (var d = 0; d < dim; d++)
  48799. result.vertices.push(data[i][j][d]);
  48800. }
  48801. if (i > 0) {
  48802. holeIndex += data[i - 1].length;
  48803. result.holes.push(holeIndex);
  48804. }
  48805. }
  48806. return result;
  48807. }
  48808. Earcut.flatten = flatten;
  48809. ;
  48810. })(Earcut || (Earcut = {}));
  48811. var BABYLON;
  48812. (function (BABYLON) {
  48813. // Unique ID when we import meshes from Babylon to CSG
  48814. var currentCSGMeshId = 0;
  48815. // # class Vertex
  48816. // Represents a vertex of a polygon. Use your own vertex class instead of this
  48817. // one to provide additional features like texture coordinates and vertex
  48818. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  48819. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  48820. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  48821. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  48822. // is not used anywhere else.
  48823. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  48824. var Vertex = (function () {
  48825. function Vertex(pos, normal, uv) {
  48826. this.pos = pos;
  48827. this.normal = normal;
  48828. this.uv = uv;
  48829. }
  48830. Vertex.prototype.clone = function () {
  48831. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  48832. };
  48833. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  48834. // orientation of a polygon is flipped.
  48835. Vertex.prototype.flip = function () {
  48836. this.normal = this.normal.scale(-1);
  48837. };
  48838. // Create a new vertex between this vertex and `other` by linearly
  48839. // interpolating all properties using a parameter of `t`. Subclasses should
  48840. // override this to interpolate additional properties.
  48841. Vertex.prototype.interpolate = function (other, t) {
  48842. 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));
  48843. };
  48844. return Vertex;
  48845. })();
  48846. // # class Plane
  48847. // Represents a plane in 3D space.
  48848. var Plane = (function () {
  48849. function Plane(normal, w) {
  48850. this.normal = normal;
  48851. this.w = w;
  48852. }
  48853. Plane.FromPoints = function (a, b, c) {
  48854. var v0 = c.subtract(a);
  48855. var v1 = b.subtract(a);
  48856. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  48857. return null;
  48858. }
  48859. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  48860. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  48861. };
  48862. Plane.prototype.clone = function () {
  48863. return new Plane(this.normal.clone(), this.w);
  48864. };
  48865. Plane.prototype.flip = function () {
  48866. this.normal.scaleInPlace(-1);
  48867. this.w = -this.w;
  48868. };
  48869. // Split `polygon` by this plane if needed, then put the polygon or polygon
  48870. // fragments in the appropriate lists. Coplanar polygons go into either
  48871. // `coplanarFront` or `coplanarBack` depending on their orientation with
  48872. // respect to this plane. Polygons in front or in back of this plane go into
  48873. // either `front` or `back`.
  48874. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  48875. var COPLANAR = 0;
  48876. var FRONT = 1;
  48877. var BACK = 2;
  48878. var SPANNING = 3;
  48879. // Classify each point as well as the entire polygon into one of the above
  48880. // four classes.
  48881. var polygonType = 0;
  48882. var types = [];
  48883. var i;
  48884. var t;
  48885. for (i = 0; i < polygon.vertices.length; i++) {
  48886. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  48887. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  48888. polygonType |= type;
  48889. types.push(type);
  48890. }
  48891. // Put the polygon in the correct list, splitting it when necessary.
  48892. switch (polygonType) {
  48893. case COPLANAR:
  48894. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  48895. break;
  48896. case FRONT:
  48897. front.push(polygon);
  48898. break;
  48899. case BACK:
  48900. back.push(polygon);
  48901. break;
  48902. case SPANNING:
  48903. var f = [], b = [];
  48904. for (i = 0; i < polygon.vertices.length; i++) {
  48905. var j = (i + 1) % polygon.vertices.length;
  48906. var ti = types[i], tj = types[j];
  48907. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  48908. if (ti !== BACK)
  48909. f.push(vi);
  48910. if (ti !== FRONT)
  48911. b.push(ti !== BACK ? vi.clone() : vi);
  48912. if ((ti | tj) === SPANNING) {
  48913. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  48914. var v = vi.interpolate(vj, t);
  48915. f.push(v);
  48916. b.push(v.clone());
  48917. }
  48918. }
  48919. var poly;
  48920. if (f.length >= 3) {
  48921. poly = new Polygon(f, polygon.shared);
  48922. if (poly.plane)
  48923. front.push(poly);
  48924. }
  48925. if (b.length >= 3) {
  48926. poly = new Polygon(b, polygon.shared);
  48927. if (poly.plane)
  48928. back.push(poly);
  48929. }
  48930. break;
  48931. }
  48932. };
  48933. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  48934. // point is on the plane.
  48935. Plane.EPSILON = 1e-5;
  48936. return Plane;
  48937. })();
  48938. // # class Polygon
  48939. // Represents a convex polygon. The vertices used to initialize a polygon must
  48940. // be coplanar and form a convex loop.
  48941. //
  48942. // Each convex polygon has a `shared` property, which is shared between all
  48943. // polygons that are clones of each other or were split from the same polygon.
  48944. // This can be used to define per-polygon properties (such as surface color).
  48945. var Polygon = (function () {
  48946. function Polygon(vertices, shared) {
  48947. this.vertices = vertices;
  48948. this.shared = shared;
  48949. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  48950. }
  48951. Polygon.prototype.clone = function () {
  48952. var vertices = this.vertices.map(function (v) { return v.clone(); });
  48953. return new Polygon(vertices, this.shared);
  48954. };
  48955. Polygon.prototype.flip = function () {
  48956. this.vertices.reverse().map(function (v) { v.flip(); });
  48957. this.plane.flip();
  48958. };
  48959. return Polygon;
  48960. })();
  48961. // # class Node
  48962. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  48963. // by picking a polygon to split along. That polygon (and all other coplanar
  48964. // polygons) are added directly to that node and the other polygons are added to
  48965. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  48966. // no distinction between internal and leaf nodes.
  48967. var Node = (function () {
  48968. function Node(polygons) {
  48969. this.plane = null;
  48970. this.front = null;
  48971. this.back = null;
  48972. this.polygons = [];
  48973. if (polygons) {
  48974. this.build(polygons);
  48975. }
  48976. }
  48977. Node.prototype.clone = function () {
  48978. var node = new Node();
  48979. node.plane = this.plane && this.plane.clone();
  48980. node.front = this.front && this.front.clone();
  48981. node.back = this.back && this.back.clone();
  48982. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  48983. return node;
  48984. };
  48985. // Convert solid space to empty space and empty space to solid space.
  48986. Node.prototype.invert = function () {
  48987. for (var i = 0; i < this.polygons.length; i++) {
  48988. this.polygons[i].flip();
  48989. }
  48990. if (this.plane) {
  48991. this.plane.flip();
  48992. }
  48993. if (this.front) {
  48994. this.front.invert();
  48995. }
  48996. if (this.back) {
  48997. this.back.invert();
  48998. }
  48999. var temp = this.front;
  49000. this.front = this.back;
  49001. this.back = temp;
  49002. };
  49003. // Recursively remove all polygons in `polygons` that are inside this BSP
  49004. // tree.
  49005. Node.prototype.clipPolygons = function (polygons) {
  49006. if (!this.plane)
  49007. return polygons.slice();
  49008. var front = [], back = [];
  49009. for (var i = 0; i < polygons.length; i++) {
  49010. this.plane.splitPolygon(polygons[i], front, back, front, back);
  49011. }
  49012. if (this.front) {
  49013. front = this.front.clipPolygons(front);
  49014. }
  49015. if (this.back) {
  49016. back = this.back.clipPolygons(back);
  49017. }
  49018. else {
  49019. back = [];
  49020. }
  49021. return front.concat(back);
  49022. };
  49023. // Remove all polygons in this BSP tree that are inside the other BSP tree
  49024. // `bsp`.
  49025. Node.prototype.clipTo = function (bsp) {
  49026. this.polygons = bsp.clipPolygons(this.polygons);
  49027. if (this.front)
  49028. this.front.clipTo(bsp);
  49029. if (this.back)
  49030. this.back.clipTo(bsp);
  49031. };
  49032. // Return a list of all polygons in this BSP tree.
  49033. Node.prototype.allPolygons = function () {
  49034. var polygons = this.polygons.slice();
  49035. if (this.front)
  49036. polygons = polygons.concat(this.front.allPolygons());
  49037. if (this.back)
  49038. polygons = polygons.concat(this.back.allPolygons());
  49039. return polygons;
  49040. };
  49041. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  49042. // new polygons are filtered down to the bottom of the tree and become new
  49043. // nodes there. Each set of polygons is partitioned using the first polygon
  49044. // (no heuristic is used to pick a good split).
  49045. Node.prototype.build = function (polygons) {
  49046. if (!polygons.length)
  49047. return;
  49048. if (!this.plane)
  49049. this.plane = polygons[0].plane.clone();
  49050. var front = [], back = [];
  49051. for (var i = 0; i < polygons.length; i++) {
  49052. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  49053. }
  49054. if (front.length) {
  49055. if (!this.front)
  49056. this.front = new Node();
  49057. this.front.build(front);
  49058. }
  49059. if (back.length) {
  49060. if (!this.back)
  49061. this.back = new Node();
  49062. this.back.build(back);
  49063. }
  49064. };
  49065. return Node;
  49066. })();
  49067. var CSG = (function () {
  49068. function CSG() {
  49069. this.polygons = new Array();
  49070. }
  49071. // Convert BABYLON.Mesh to BABYLON.CSG
  49072. CSG.FromMesh = function (mesh) {
  49073. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  49074. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  49075. if (mesh instanceof BABYLON.Mesh) {
  49076. mesh.computeWorldMatrix(true);
  49077. matrix = mesh.getWorldMatrix();
  49078. meshPosition = mesh.position.clone();
  49079. meshRotation = mesh.rotation.clone();
  49080. if (mesh.rotationQuaternion) {
  49081. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  49082. }
  49083. meshScaling = mesh.scaling.clone();
  49084. }
  49085. else {
  49086. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  49087. }
  49088. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49089. var subMeshes = mesh.subMeshes;
  49090. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  49091. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  49092. vertices = [];
  49093. for (var j = 0; j < 3; j++) {
  49094. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  49095. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  49096. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  49097. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  49098. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  49099. vertex = new Vertex(position, normal, uv);
  49100. vertices.push(vertex);
  49101. }
  49102. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  49103. // To handle the case of degenerated triangle
  49104. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  49105. if (polygon.plane)
  49106. polygons.push(polygon);
  49107. }
  49108. }
  49109. var csg = CSG.FromPolygons(polygons);
  49110. csg.matrix = matrix;
  49111. csg.position = meshPosition;
  49112. csg.rotation = meshRotation;
  49113. csg.scaling = meshScaling;
  49114. csg.rotationQuaternion = meshRotationQuaternion;
  49115. currentCSGMeshId++;
  49116. return csg;
  49117. };
  49118. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  49119. CSG.FromPolygons = function (polygons) {
  49120. var csg = new CSG();
  49121. csg.polygons = polygons;
  49122. return csg;
  49123. };
  49124. CSG.prototype.clone = function () {
  49125. var csg = new CSG();
  49126. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  49127. csg.copyTransformAttributes(this);
  49128. return csg;
  49129. };
  49130. CSG.prototype.toPolygons = function () {
  49131. return this.polygons;
  49132. };
  49133. CSG.prototype.union = function (csg) {
  49134. var a = new Node(this.clone().polygons);
  49135. var b = new Node(csg.clone().polygons);
  49136. a.clipTo(b);
  49137. b.clipTo(a);
  49138. b.invert();
  49139. b.clipTo(a);
  49140. b.invert();
  49141. a.build(b.allPolygons());
  49142. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49143. };
  49144. CSG.prototype.unionInPlace = function (csg) {
  49145. var a = new Node(this.polygons);
  49146. var b = new Node(csg.polygons);
  49147. a.clipTo(b);
  49148. b.clipTo(a);
  49149. b.invert();
  49150. b.clipTo(a);
  49151. b.invert();
  49152. a.build(b.allPolygons());
  49153. this.polygons = a.allPolygons();
  49154. };
  49155. CSG.prototype.subtract = function (csg) {
  49156. var a = new Node(this.clone().polygons);
  49157. var b = new Node(csg.clone().polygons);
  49158. a.invert();
  49159. a.clipTo(b);
  49160. b.clipTo(a);
  49161. b.invert();
  49162. b.clipTo(a);
  49163. b.invert();
  49164. a.build(b.allPolygons());
  49165. a.invert();
  49166. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49167. };
  49168. CSG.prototype.subtractInPlace = function (csg) {
  49169. var a = new Node(this.polygons);
  49170. var b = new Node(csg.polygons);
  49171. a.invert();
  49172. a.clipTo(b);
  49173. b.clipTo(a);
  49174. b.invert();
  49175. b.clipTo(a);
  49176. b.invert();
  49177. a.build(b.allPolygons());
  49178. a.invert();
  49179. this.polygons = a.allPolygons();
  49180. };
  49181. CSG.prototype.intersect = function (csg) {
  49182. var a = new Node(this.clone().polygons);
  49183. var b = new Node(csg.clone().polygons);
  49184. a.invert();
  49185. b.clipTo(a);
  49186. b.invert();
  49187. a.clipTo(b);
  49188. b.clipTo(a);
  49189. a.build(b.allPolygons());
  49190. a.invert();
  49191. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49192. };
  49193. CSG.prototype.intersectInPlace = function (csg) {
  49194. var a = new Node(this.polygons);
  49195. var b = new Node(csg.polygons);
  49196. a.invert();
  49197. b.clipTo(a);
  49198. b.invert();
  49199. a.clipTo(b);
  49200. b.clipTo(a);
  49201. a.build(b.allPolygons());
  49202. a.invert();
  49203. this.polygons = a.allPolygons();
  49204. };
  49205. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  49206. // not modified.
  49207. CSG.prototype.inverse = function () {
  49208. var csg = this.clone();
  49209. csg.inverseInPlace();
  49210. return csg;
  49211. };
  49212. CSG.prototype.inverseInPlace = function () {
  49213. this.polygons.map(function (p) { p.flip(); });
  49214. };
  49215. // This is used to keep meshes transformations so they can be restored
  49216. // when we build back a Babylon Mesh
  49217. // NB : All CSG operations are performed in world coordinates
  49218. CSG.prototype.copyTransformAttributes = function (csg) {
  49219. this.matrix = csg.matrix;
  49220. this.position = csg.position;
  49221. this.rotation = csg.rotation;
  49222. this.scaling = csg.scaling;
  49223. this.rotationQuaternion = csg.rotationQuaternion;
  49224. return this;
  49225. };
  49226. // Build Raw mesh from CSG
  49227. // Coordinates here are in world space
  49228. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  49229. var matrix = this.matrix.clone();
  49230. matrix.invert();
  49231. 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;
  49232. if (keepSubMeshes) {
  49233. // Sort Polygons, since subMeshes are indices range
  49234. polygons.sort(function (a, b) {
  49235. if (a.shared.meshId === b.shared.meshId) {
  49236. return a.shared.subMeshId - b.shared.subMeshId;
  49237. }
  49238. else {
  49239. return a.shared.meshId - b.shared.meshId;
  49240. }
  49241. });
  49242. }
  49243. for (var i = 0, il = polygons.length; i < il; i++) {
  49244. polygon = polygons[i];
  49245. // Building SubMeshes
  49246. if (!subMesh_dict[polygon.shared.meshId]) {
  49247. subMesh_dict[polygon.shared.meshId] = {};
  49248. }
  49249. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  49250. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  49251. indexStart: +Infinity,
  49252. indexEnd: -Infinity,
  49253. materialIndex: polygon.shared.materialIndex
  49254. };
  49255. }
  49256. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  49257. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  49258. polygonIndices[0] = 0;
  49259. polygonIndices[1] = j - 1;
  49260. polygonIndices[2] = j;
  49261. for (var k = 0; k < 3; k++) {
  49262. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  49263. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  49264. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  49265. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  49266. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  49267. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  49268. // Check if 2 points can be merged
  49269. if (!(typeof vertex_idx !== 'undefined' &&
  49270. normals[vertex_idx * 3] === localNormal.x &&
  49271. normals[vertex_idx * 3 + 1] === localNormal.y &&
  49272. normals[vertex_idx * 3 + 2] === localNormal.z &&
  49273. uvs[vertex_idx * 2] === uv.x &&
  49274. uvs[vertex_idx * 2 + 1] === uv.y)) {
  49275. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  49276. uvs.push(uv.x, uv.y);
  49277. normals.push(normal.x, normal.y, normal.z);
  49278. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  49279. }
  49280. indices.push(vertex_idx);
  49281. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  49282. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  49283. currentIndex++;
  49284. }
  49285. }
  49286. }
  49287. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  49288. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  49289. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  49290. mesh.setIndices(indices);
  49291. if (keepSubMeshes) {
  49292. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  49293. var materialIndexOffset = 0, materialMaxIndex;
  49294. mesh.subMeshes = new Array();
  49295. for (var m in subMesh_dict) {
  49296. materialMaxIndex = -1;
  49297. for (var sm in subMesh_dict[m]) {
  49298. subMesh_obj = subMesh_dict[m][sm];
  49299. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  49300. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  49301. }
  49302. materialIndexOffset += ++materialMaxIndex;
  49303. }
  49304. }
  49305. return mesh;
  49306. };
  49307. // Build Mesh from CSG taking material and transforms into account
  49308. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  49309. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  49310. mesh.material = material;
  49311. mesh.position.copyFrom(this.position);
  49312. mesh.rotation.copyFrom(this.rotation);
  49313. if (this.rotationQuaternion) {
  49314. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  49315. }
  49316. mesh.scaling.copyFrom(this.scaling);
  49317. mesh.computeWorldMatrix(true);
  49318. return mesh;
  49319. };
  49320. return CSG;
  49321. })();
  49322. BABYLON.CSG = CSG;
  49323. })(BABYLON || (BABYLON = {}));
  49324. var BABYLON;
  49325. (function (BABYLON) {
  49326. var VRDistortionCorrectionPostProcess = (function (_super) {
  49327. __extends(VRDistortionCorrectionPostProcess, _super);
  49328. //ANY
  49329. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  49330. var _this = this;
  49331. _super.call(this, name, "vrDistortionCorrection", [
  49332. 'LensCenter',
  49333. 'Scale',
  49334. 'ScaleIn',
  49335. 'HmdWarpParam'
  49336. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  49337. this._isRightEye = isRightEye;
  49338. this._distortionFactors = vrMetrics.distortionK;
  49339. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  49340. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  49341. this.onSizeChangedObservable.add(function () {
  49342. _this.aspectRatio = _this.width * .5 / _this.height;
  49343. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  49344. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  49345. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  49346. });
  49347. this.onApplyObservable.add(function (effect) {
  49348. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  49349. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  49350. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  49351. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  49352. });
  49353. }
  49354. return VRDistortionCorrectionPostProcess;
  49355. })(BABYLON.PostProcess);
  49356. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  49357. })(BABYLON || (BABYLON = {}));
  49358. // Mainly based on these 2 articles :
  49359. // 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
  49360. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  49361. var BABYLON;
  49362. (function (BABYLON) {
  49363. (function (JoystickAxis) {
  49364. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  49365. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  49366. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  49367. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  49368. var JoystickAxis = BABYLON.JoystickAxis;
  49369. var VirtualJoystick = (function () {
  49370. function VirtualJoystick(leftJoystick) {
  49371. var _this = this;
  49372. if (leftJoystick) {
  49373. this._leftJoystick = true;
  49374. }
  49375. else {
  49376. this._leftJoystick = false;
  49377. }
  49378. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  49379. VirtualJoystick._globalJoystickIndex++;
  49380. // By default left & right arrow keys are moving the X
  49381. // and up & down keys are moving the Y
  49382. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49383. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49384. this.reverseLeftRight = false;
  49385. this.reverseUpDown = false;
  49386. // collections of pointers
  49387. this._touches = new BABYLON.StringDictionary();
  49388. this.deltaPosition = BABYLON.Vector3.Zero();
  49389. this._joystickSensibility = 25;
  49390. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49391. this._rotationSpeed = 25;
  49392. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  49393. this._rotateOnAxisRelativeToMesh = false;
  49394. this._onResize = function (evt) {
  49395. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49396. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49397. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  49398. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  49399. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  49400. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  49401. };
  49402. // injecting a canvas element on top of the canvas 3D game
  49403. if (!VirtualJoystick.vjCanvas) {
  49404. window.addEventListener("resize", this._onResize, false);
  49405. VirtualJoystick.vjCanvas = document.createElement("canvas");
  49406. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49407. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49408. VirtualJoystick.vjCanvas.width = window.innerWidth;
  49409. VirtualJoystick.vjCanvas.height = window.innerHeight;
  49410. VirtualJoystick.vjCanvas.style.width = "100%";
  49411. VirtualJoystick.vjCanvas.style.height = "100%";
  49412. VirtualJoystick.vjCanvas.style.position = "absolute";
  49413. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  49414. VirtualJoystick.vjCanvas.style.top = "0px";
  49415. VirtualJoystick.vjCanvas.style.left = "0px";
  49416. VirtualJoystick.vjCanvas.style.zIndex = "5";
  49417. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  49418. // Support for jQuery PEP polyfill
  49419. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  49420. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  49421. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  49422. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49423. document.body.appendChild(VirtualJoystick.vjCanvas);
  49424. }
  49425. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  49426. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  49427. this.pressed = false;
  49428. // default joystick color
  49429. this._joystickColor = "cyan";
  49430. this._joystickPointerID = -1;
  49431. // current joystick position
  49432. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  49433. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  49434. // origin joystick position
  49435. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  49436. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  49437. this._onPointerDownHandlerRef = function (evt) {
  49438. _this._onPointerDown(evt);
  49439. };
  49440. this._onPointerMoveHandlerRef = function (evt) {
  49441. _this._onPointerMove(evt);
  49442. };
  49443. this._onPointerOutHandlerRef = function (evt) {
  49444. _this._onPointerUp(evt);
  49445. };
  49446. this._onPointerUpHandlerRef = function (evt) {
  49447. _this._onPointerUp(evt);
  49448. };
  49449. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  49450. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  49451. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  49452. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  49453. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  49454. evt.preventDefault(); // Disables system menu
  49455. }, false);
  49456. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49457. }
  49458. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  49459. this._joystickSensibility = newJoystickSensibility;
  49460. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49461. };
  49462. VirtualJoystick.prototype._onPointerDown = function (e) {
  49463. var positionOnScreenCondition;
  49464. e.preventDefault();
  49465. if (this._leftJoystick === true) {
  49466. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  49467. }
  49468. else {
  49469. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  49470. }
  49471. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  49472. // First contact will be dedicated to the virtual joystick
  49473. this._joystickPointerID = e.pointerId;
  49474. this._joystickPointerStartPos.x = e.clientX;
  49475. this._joystickPointerStartPos.y = e.clientY;
  49476. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  49477. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  49478. this._deltaJoystickVector.x = 0;
  49479. this._deltaJoystickVector.y = 0;
  49480. this.pressed = true;
  49481. this._touches.add(e.pointerId.toString(), e);
  49482. }
  49483. else {
  49484. // You can only trigger the action buttons with a joystick declared
  49485. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  49486. this._action();
  49487. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  49488. }
  49489. }
  49490. };
  49491. VirtualJoystick.prototype._onPointerMove = function (e) {
  49492. // If the current pointer is the one associated to the joystick (first touch contact)
  49493. if (this._joystickPointerID == e.pointerId) {
  49494. this._joystickPointerPos.x = e.clientX;
  49495. this._joystickPointerPos.y = e.clientY;
  49496. this._deltaJoystickVector = this._joystickPointerPos.clone();
  49497. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  49498. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  49499. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  49500. switch (this._axisTargetedByLeftAndRight) {
  49501. case JoystickAxis.X:
  49502. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  49503. break;
  49504. case JoystickAxis.Y:
  49505. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  49506. break;
  49507. case JoystickAxis.Z:
  49508. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  49509. break;
  49510. }
  49511. var directionUpDown = this.reverseUpDown ? 1 : -1;
  49512. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  49513. switch (this._axisTargetedByUpAndDown) {
  49514. case JoystickAxis.X:
  49515. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  49516. break;
  49517. case JoystickAxis.Y:
  49518. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  49519. break;
  49520. case JoystickAxis.Z:
  49521. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  49522. break;
  49523. }
  49524. }
  49525. else {
  49526. var data = this._touches.get(e.pointerId.toString());
  49527. if (data) {
  49528. data.x = e.clientX;
  49529. data.y = e.clientY;
  49530. }
  49531. }
  49532. };
  49533. VirtualJoystick.prototype._onPointerUp = function (e) {
  49534. if (this._joystickPointerID == e.pointerId) {
  49535. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  49536. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  49537. this._joystickPointerID = -1;
  49538. this.pressed = false;
  49539. }
  49540. else {
  49541. var touch = this._touches.get(e.pointerId.toString());
  49542. if (touch) {
  49543. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  49544. }
  49545. }
  49546. this._deltaJoystickVector.x = 0;
  49547. this._deltaJoystickVector.y = 0;
  49548. this._touches.remove(e.pointerId.toString());
  49549. };
  49550. /**
  49551. * Change the color of the virtual joystick
  49552. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  49553. */
  49554. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  49555. this._joystickColor = newColor;
  49556. };
  49557. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  49558. this._action = action;
  49559. };
  49560. // Define which axis you'd like to control for left & right
  49561. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  49562. switch (axis) {
  49563. case JoystickAxis.X:
  49564. case JoystickAxis.Y:
  49565. case JoystickAxis.Z:
  49566. this._axisTargetedByLeftAndRight = axis;
  49567. break;
  49568. default:
  49569. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49570. break;
  49571. }
  49572. };
  49573. // Define which axis you'd like to control for up & down
  49574. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  49575. switch (axis) {
  49576. case JoystickAxis.X:
  49577. case JoystickAxis.Y:
  49578. case JoystickAxis.Z:
  49579. this._axisTargetedByUpAndDown = axis;
  49580. break;
  49581. default:
  49582. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49583. break;
  49584. }
  49585. };
  49586. VirtualJoystick.prototype._clearCanvas = function () {
  49587. if (this._leftJoystick) {
  49588. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  49589. }
  49590. else {
  49591. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  49592. }
  49593. };
  49594. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  49595. var _this = this;
  49596. if (this.pressed) {
  49597. this._touches.forEach(function (touch) {
  49598. if (touch.pointerId === _this._joystickPointerID) {
  49599. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  49600. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  49601. VirtualJoystick.vjCanvasContext.beginPath();
  49602. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49603. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49604. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  49605. VirtualJoystick.vjCanvasContext.stroke();
  49606. VirtualJoystick.vjCanvasContext.closePath();
  49607. VirtualJoystick.vjCanvasContext.beginPath();
  49608. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49609. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  49610. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  49611. VirtualJoystick.vjCanvasContext.stroke();
  49612. VirtualJoystick.vjCanvasContext.closePath();
  49613. VirtualJoystick.vjCanvasContext.beginPath();
  49614. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  49615. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  49616. VirtualJoystick.vjCanvasContext.stroke();
  49617. VirtualJoystick.vjCanvasContext.closePath();
  49618. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  49619. }
  49620. else {
  49621. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  49622. VirtualJoystick.vjCanvasContext.beginPath();
  49623. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  49624. VirtualJoystick.vjCanvasContext.beginPath();
  49625. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  49626. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  49627. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  49628. VirtualJoystick.vjCanvasContext.stroke();
  49629. VirtualJoystick.vjCanvasContext.closePath();
  49630. touch.prevX = touch.x;
  49631. touch.prevY = touch.y;
  49632. }
  49633. ;
  49634. });
  49635. }
  49636. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  49637. };
  49638. VirtualJoystick.prototype.releaseCanvas = function () {
  49639. if (VirtualJoystick.vjCanvas) {
  49640. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  49641. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  49642. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  49643. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  49644. window.removeEventListener("resize", this._onResize);
  49645. document.body.removeChild(VirtualJoystick.vjCanvas);
  49646. VirtualJoystick.vjCanvas = null;
  49647. }
  49648. };
  49649. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  49650. VirtualJoystick._globalJoystickIndex = 0;
  49651. return VirtualJoystick;
  49652. })();
  49653. BABYLON.VirtualJoystick = VirtualJoystick;
  49654. })(BABYLON || (BABYLON = {}));
  49655. var BABYLON;
  49656. (function (BABYLON) {
  49657. // We're mainly based on the logic defined into the FreeCamera code
  49658. var VirtualJoysticksCamera = (function (_super) {
  49659. __extends(VirtualJoysticksCamera, _super);
  49660. function VirtualJoysticksCamera(name, position, scene) {
  49661. _super.call(this, name, position, scene);
  49662. this.inputs.addVirtualJoystick();
  49663. }
  49664. return VirtualJoysticksCamera;
  49665. })(BABYLON.FreeCamera);
  49666. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  49667. })(BABYLON || (BABYLON = {}));
  49668. var BABYLON;
  49669. (function (BABYLON) {
  49670. var FreeCameraVirtualJoystickInput = (function () {
  49671. function FreeCameraVirtualJoystickInput() {
  49672. }
  49673. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  49674. return this._leftjoystick;
  49675. };
  49676. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  49677. return this._rightjoystick;
  49678. };
  49679. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  49680. if (this._leftjoystick) {
  49681. var camera = this.camera;
  49682. var speed = camera._computeLocalCameraSpeed() * 50;
  49683. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  49684. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  49685. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  49686. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  49687. if (!this._leftjoystick.pressed) {
  49688. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  49689. }
  49690. if (!this._rightjoystick.pressed) {
  49691. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  49692. }
  49693. }
  49694. };
  49695. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  49696. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  49697. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  49698. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  49699. this._leftjoystick.setJoystickSensibility(0.15);
  49700. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  49701. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  49702. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  49703. this._rightjoystick.reverseUpDown = true;
  49704. this._rightjoystick.setJoystickSensibility(0.05);
  49705. this._rightjoystick.setJoystickColor("yellow");
  49706. };
  49707. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  49708. this._leftjoystick.releaseCanvas();
  49709. this._rightjoystick.releaseCanvas();
  49710. };
  49711. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  49712. return "FreeCameraVirtualJoystickInput";
  49713. };
  49714. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  49715. return "virtualJoystick";
  49716. };
  49717. return FreeCameraVirtualJoystickInput;
  49718. })();
  49719. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  49720. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  49721. })(BABYLON || (BABYLON = {}));
  49722. var BABYLON;
  49723. (function (BABYLON) {
  49724. var AnaglyphPostProcess = (function (_super) {
  49725. __extends(AnaglyphPostProcess, _super);
  49726. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  49727. var _this = this;
  49728. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  49729. this._passedProcess = rigCameras[0]._rigPostProcess;
  49730. this.onApplyObservable.add(function (effect) {
  49731. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  49732. });
  49733. }
  49734. return AnaglyphPostProcess;
  49735. })(BABYLON.PostProcess);
  49736. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  49737. })(BABYLON || (BABYLON = {}));
  49738. var BABYLON;
  49739. (function (BABYLON) {
  49740. var OutlineRenderer = (function () {
  49741. function OutlineRenderer(scene) {
  49742. this._scene = scene;
  49743. }
  49744. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  49745. var _this = this;
  49746. if (useOverlay === void 0) { useOverlay = false; }
  49747. var scene = this._scene;
  49748. var engine = this._scene.getEngine();
  49749. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49750. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  49751. return;
  49752. }
  49753. var mesh = subMesh.getRenderingMesh();
  49754. var material = subMesh.getMaterial();
  49755. engine.enableEffect(this._effect);
  49756. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  49757. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  49758. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49759. // Bones
  49760. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49761. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49762. }
  49763. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49764. // Alpha test
  49765. if (material && material.needAlphaTesting()) {
  49766. var alphaTexture = material.getAlphaTestTexture();
  49767. this._effect.setTexture("diffuseSampler", alphaTexture);
  49768. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49769. }
  49770. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  49771. };
  49772. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  49773. var defines = [];
  49774. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  49775. var mesh = subMesh.getMesh();
  49776. var material = subMesh.getMaterial();
  49777. // Alpha test
  49778. if (material && material.needAlphaTesting()) {
  49779. defines.push("#define ALPHATEST");
  49780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49781. attribs.push(BABYLON.VertexBuffer.UVKind);
  49782. defines.push("#define UV1");
  49783. }
  49784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49785. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49786. defines.push("#define UV2");
  49787. }
  49788. }
  49789. // Bones
  49790. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49793. if (mesh.numBoneInfluencers > 4) {
  49794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49796. }
  49797. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49798. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49799. }
  49800. else {
  49801. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49802. }
  49803. // Instances
  49804. if (useInstances) {
  49805. defines.push("#define INSTANCES");
  49806. attribs.push("world0");
  49807. attribs.push("world1");
  49808. attribs.push("world2");
  49809. attribs.push("world3");
  49810. }
  49811. // Get correct effect
  49812. var join = defines.join("\n");
  49813. if (this._cachedDefines !== join) {
  49814. this._cachedDefines = join;
  49815. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  49816. }
  49817. return this._effect.isReady();
  49818. };
  49819. return OutlineRenderer;
  49820. })();
  49821. BABYLON.OutlineRenderer = OutlineRenderer;
  49822. })(BABYLON || (BABYLON = {}));
  49823. var BABYLON;
  49824. (function (BABYLON) {
  49825. var MeshAssetTask = (function () {
  49826. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  49827. this.name = name;
  49828. this.meshesNames = meshesNames;
  49829. this.rootUrl = rootUrl;
  49830. this.sceneFilename = sceneFilename;
  49831. this.isCompleted = false;
  49832. }
  49833. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49834. var _this = this;
  49835. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  49836. _this.loadedMeshes = meshes;
  49837. _this.loadedParticleSystems = particleSystems;
  49838. _this.loadedSkeletons = skeletons;
  49839. _this.isCompleted = true;
  49840. if (_this.onSuccess) {
  49841. _this.onSuccess(_this);
  49842. }
  49843. onSuccess();
  49844. }, null, function () {
  49845. if (_this.onError) {
  49846. _this.onError(_this);
  49847. }
  49848. onError();
  49849. });
  49850. };
  49851. return MeshAssetTask;
  49852. })();
  49853. BABYLON.MeshAssetTask = MeshAssetTask;
  49854. var TextFileAssetTask = (function () {
  49855. function TextFileAssetTask(name, url) {
  49856. this.name = name;
  49857. this.url = url;
  49858. this.isCompleted = false;
  49859. }
  49860. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49861. var _this = this;
  49862. BABYLON.Tools.LoadFile(this.url, function (data) {
  49863. _this.text = data;
  49864. _this.isCompleted = true;
  49865. if (_this.onSuccess) {
  49866. _this.onSuccess(_this);
  49867. }
  49868. onSuccess();
  49869. }, null, scene.database, false, function () {
  49870. if (_this.onError) {
  49871. _this.onError(_this);
  49872. }
  49873. onError();
  49874. });
  49875. };
  49876. return TextFileAssetTask;
  49877. })();
  49878. BABYLON.TextFileAssetTask = TextFileAssetTask;
  49879. var BinaryFileAssetTask = (function () {
  49880. function BinaryFileAssetTask(name, url) {
  49881. this.name = name;
  49882. this.url = url;
  49883. this.isCompleted = false;
  49884. }
  49885. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49886. var _this = this;
  49887. BABYLON.Tools.LoadFile(this.url, function (data) {
  49888. _this.data = data;
  49889. _this.isCompleted = true;
  49890. if (_this.onSuccess) {
  49891. _this.onSuccess(_this);
  49892. }
  49893. onSuccess();
  49894. }, null, scene.database, true, function () {
  49895. if (_this.onError) {
  49896. _this.onError(_this);
  49897. }
  49898. onError();
  49899. });
  49900. };
  49901. return BinaryFileAssetTask;
  49902. })();
  49903. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  49904. var ImageAssetTask = (function () {
  49905. function ImageAssetTask(name, url) {
  49906. this.name = name;
  49907. this.url = url;
  49908. this.isCompleted = false;
  49909. }
  49910. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49911. var _this = this;
  49912. var img = new Image();
  49913. img.onload = function () {
  49914. _this.image = img;
  49915. _this.isCompleted = true;
  49916. if (_this.onSuccess) {
  49917. _this.onSuccess(_this);
  49918. }
  49919. onSuccess();
  49920. };
  49921. img.onerror = function () {
  49922. if (_this.onError) {
  49923. _this.onError(_this);
  49924. }
  49925. onError();
  49926. };
  49927. img.src = this.url;
  49928. };
  49929. return ImageAssetTask;
  49930. })();
  49931. BABYLON.ImageAssetTask = ImageAssetTask;
  49932. var TextureAssetTask = (function () {
  49933. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  49934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49935. this.name = name;
  49936. this.url = url;
  49937. this.noMipmap = noMipmap;
  49938. this.invertY = invertY;
  49939. this.samplingMode = samplingMode;
  49940. this.isCompleted = false;
  49941. }
  49942. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49943. var _this = this;
  49944. var onload = function () {
  49945. _this.isCompleted = true;
  49946. if (_this.onSuccess) {
  49947. _this.onSuccess(_this);
  49948. }
  49949. onSuccess();
  49950. };
  49951. var onerror = function () {
  49952. if (_this.onError) {
  49953. _this.onError(_this);
  49954. }
  49955. onError();
  49956. };
  49957. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  49958. };
  49959. return TextureAssetTask;
  49960. })();
  49961. BABYLON.TextureAssetTask = TextureAssetTask;
  49962. var AssetsManager = (function () {
  49963. function AssetsManager(scene) {
  49964. this._tasks = new Array();
  49965. this._waitingTasksCount = 0;
  49966. this.useDefaultLoadingScreen = true;
  49967. this._scene = scene;
  49968. }
  49969. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  49970. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  49971. this._tasks.push(task);
  49972. return task;
  49973. };
  49974. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49975. var task = new TextFileAssetTask(taskName, url);
  49976. this._tasks.push(task);
  49977. return task;
  49978. };
  49979. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49980. var task = new BinaryFileAssetTask(taskName, url);
  49981. this._tasks.push(task);
  49982. return task;
  49983. };
  49984. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49985. var task = new ImageAssetTask(taskName, url);
  49986. this._tasks.push(task);
  49987. return task;
  49988. };
  49989. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49991. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49992. this._tasks.push(task);
  49993. return task;
  49994. };
  49995. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49996. this._waitingTasksCount--;
  49997. if (this._waitingTasksCount === 0) {
  49998. if (this.onFinish) {
  49999. this.onFinish(this._tasks);
  50000. }
  50001. this._scene.getEngine().hideLoadingUI();
  50002. }
  50003. };
  50004. AssetsManager.prototype._runTask = function (task) {
  50005. var _this = this;
  50006. task.run(this._scene, function () {
  50007. if (_this.onTaskSuccess) {
  50008. _this.onTaskSuccess(task);
  50009. }
  50010. _this._decreaseWaitingTasksCount();
  50011. }, function () {
  50012. if (_this.onTaskError) {
  50013. _this.onTaskError(task);
  50014. }
  50015. _this._decreaseWaitingTasksCount();
  50016. });
  50017. };
  50018. AssetsManager.prototype.reset = function () {
  50019. this._tasks = new Array();
  50020. return this;
  50021. };
  50022. AssetsManager.prototype.load = function () {
  50023. this._waitingTasksCount = this._tasks.length;
  50024. if (this._waitingTasksCount === 0) {
  50025. if (this.onFinish) {
  50026. this.onFinish(this._tasks);
  50027. }
  50028. return this;
  50029. }
  50030. if (this.useDefaultLoadingScreen) {
  50031. this._scene.getEngine().displayLoadingUI();
  50032. }
  50033. for (var index = 0; index < this._tasks.length; index++) {
  50034. var task = this._tasks[index];
  50035. this._runTask(task);
  50036. }
  50037. return this;
  50038. };
  50039. return AssetsManager;
  50040. })();
  50041. BABYLON.AssetsManager = AssetsManager;
  50042. })(BABYLON || (BABYLON = {}));
  50043. var BABYLON;
  50044. (function (BABYLON) {
  50045. var VRCameraMetrics = (function () {
  50046. function VRCameraMetrics() {
  50047. this.compensateDistortion = true;
  50048. }
  50049. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  50050. get: function () {
  50051. return this.hResolution / (2 * this.vResolution);
  50052. },
  50053. enumerable: true,
  50054. configurable: true
  50055. });
  50056. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  50057. get: function () {
  50058. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  50064. get: function () {
  50065. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50066. var h = (4 * meters) / this.hScreenSize;
  50067. return BABYLON.Matrix.Translation(h, 0, 0);
  50068. },
  50069. enumerable: true,
  50070. configurable: true
  50071. });
  50072. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  50073. get: function () {
  50074. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50075. var h = (4 * meters) / this.hScreenSize;
  50076. return BABYLON.Matrix.Translation(-h, 0, 0);
  50077. },
  50078. enumerable: true,
  50079. configurable: true
  50080. });
  50081. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  50082. get: function () {
  50083. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  50084. },
  50085. enumerable: true,
  50086. configurable: true
  50087. });
  50088. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  50089. get: function () {
  50090. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  50091. },
  50092. enumerable: true,
  50093. configurable: true
  50094. });
  50095. VRCameraMetrics.GetDefault = function () {
  50096. var result = new VRCameraMetrics();
  50097. result.hResolution = 1280;
  50098. result.vResolution = 800;
  50099. result.hScreenSize = 0.149759993;
  50100. result.vScreenSize = 0.0935999975;
  50101. result.vScreenCenter = 0.0467999987,
  50102. result.eyeToScreenDistance = 0.0410000011;
  50103. result.lensSeparationDistance = 0.0635000020;
  50104. result.interpupillaryDistance = 0.0640000030;
  50105. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  50106. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  50107. result.postProcessScaleFactor = 1.714605507808412;
  50108. result.lensCenterOffset = 0.151976421;
  50109. return result;
  50110. };
  50111. return VRCameraMetrics;
  50112. })();
  50113. BABYLON.VRCameraMetrics = VRCameraMetrics;
  50114. })(BABYLON || (BABYLON = {}));
  50115. var BABYLON;
  50116. (function (BABYLON) {
  50117. var VRDeviceOrientationFreeCamera = (function (_super) {
  50118. __extends(VRDeviceOrientationFreeCamera, _super);
  50119. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  50120. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50121. _super.call(this, name, position, scene);
  50122. this.rotationQuaternion = new BABYLON.Quaternion();
  50123. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50124. metrics.compensateDistortion = compensateDistortion;
  50125. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50126. this.inputs.addDeviceOrientation();
  50127. }
  50128. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  50129. return "VRDeviceOrientationFreeCamera";
  50130. };
  50131. return VRDeviceOrientationFreeCamera;
  50132. })(BABYLON.FreeCamera);
  50133. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50134. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50135. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50136. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  50137. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50138. _super.call(this, name, alpha, beta, radius, target, scene);
  50139. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50140. metrics.compensateDistortion = compensateDistortion;
  50141. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50142. this.inputs.addVRDeviceOrientation();
  50143. }
  50144. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  50145. return "VRDeviceOrientationArcRotateCamera";
  50146. };
  50147. return VRDeviceOrientationArcRotateCamera;
  50148. })(BABYLON.ArcRotateCamera);
  50149. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50150. })(BABYLON || (BABYLON = {}));
  50151. var BABYLON;
  50152. (function (BABYLON) {
  50153. var WebVRFreeCamera = (function (_super) {
  50154. __extends(WebVRFreeCamera, _super);
  50155. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  50156. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50157. _super.call(this, name, position, scene);
  50158. this._hmdDevice = null;
  50159. this._sensorDevice = null;
  50160. this._cacheState = null;
  50161. this._vrEnabled = false;
  50162. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50163. metrics.compensateDistortion = compensateDistortion;
  50164. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50165. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  50166. this.rotationQuaternion = new BABYLON.Quaternion();
  50167. }
  50168. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  50169. var size = devices.length;
  50170. var i = 0;
  50171. // Reset devices.
  50172. this._sensorDevice = null;
  50173. this._hmdDevice = null;
  50174. // Search for a HmdDevice.
  50175. while (i < size && this._hmdDevice === null) {
  50176. if (devices[i] instanceof HMDVRDevice) {
  50177. this._hmdDevice = devices[i];
  50178. }
  50179. i++;
  50180. }
  50181. i = 0;
  50182. while (i < size && this._sensorDevice === null) {
  50183. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  50184. this._sensorDevice = devices[i];
  50185. }
  50186. i++;
  50187. }
  50188. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  50189. };
  50190. WebVRFreeCamera.prototype._checkInputs = function () {
  50191. if (this._vrEnabled) {
  50192. this._cacheState = this._sensorDevice.getState();
  50193. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  50194. //Flip in XY plane
  50195. this.rotationQuaternion.z *= -1;
  50196. this.rotationQuaternion.w *= -1;
  50197. }
  50198. _super.prototype._checkInputs.call(this);
  50199. };
  50200. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  50201. _super.prototype.attachControl.call(this, element, noPreventDefault);
  50202. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  50203. if (navigator.getVRDevices) {
  50204. navigator.getVRDevices().then(this._getWebVRDevices);
  50205. }
  50206. else if (navigator.mozGetVRDevices) {
  50207. navigator.mozGetVRDevices(this._getWebVRDevices);
  50208. }
  50209. };
  50210. WebVRFreeCamera.prototype.detachControl = function (element) {
  50211. _super.prototype.detachControl.call(this, element);
  50212. this._vrEnabled = false;
  50213. };
  50214. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  50215. if (!this._hmdDevice)
  50216. return;
  50217. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  50218. };
  50219. WebVRFreeCamera.prototype.getTypeName = function () {
  50220. return "WebVRFreeCamera";
  50221. };
  50222. return WebVRFreeCamera;
  50223. })(BABYLON.FreeCamera);
  50224. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  50225. })(BABYLON || (BABYLON = {}));
  50226. var BABYLON;
  50227. (function (BABYLON) {
  50228. // Standard optimizations
  50229. var SceneOptimization = (function () {
  50230. function SceneOptimization(priority) {
  50231. if (priority === void 0) { priority = 0; }
  50232. this.priority = priority;
  50233. this.apply = function (scene) {
  50234. return true; // Return true if everything that can be done was applied
  50235. };
  50236. }
  50237. return SceneOptimization;
  50238. })();
  50239. BABYLON.SceneOptimization = SceneOptimization;
  50240. var TextureOptimization = (function (_super) {
  50241. __extends(TextureOptimization, _super);
  50242. function TextureOptimization(priority, maximumSize) {
  50243. var _this = this;
  50244. if (priority === void 0) { priority = 0; }
  50245. if (maximumSize === void 0) { maximumSize = 1024; }
  50246. _super.call(this, priority);
  50247. this.priority = priority;
  50248. this.maximumSize = maximumSize;
  50249. this.apply = function (scene) {
  50250. var allDone = true;
  50251. for (var index = 0; index < scene.textures.length; index++) {
  50252. var texture = scene.textures[index];
  50253. if (!texture.canRescale) {
  50254. continue;
  50255. }
  50256. var currentSize = texture.getSize();
  50257. var maxDimension = Math.max(currentSize.width, currentSize.height);
  50258. if (maxDimension > _this.maximumSize) {
  50259. texture.scale(0.5);
  50260. allDone = false;
  50261. }
  50262. }
  50263. return allDone;
  50264. };
  50265. }
  50266. return TextureOptimization;
  50267. })(SceneOptimization);
  50268. BABYLON.TextureOptimization = TextureOptimization;
  50269. var HardwareScalingOptimization = (function (_super) {
  50270. __extends(HardwareScalingOptimization, _super);
  50271. function HardwareScalingOptimization(priority, maximumScale) {
  50272. var _this = this;
  50273. if (priority === void 0) { priority = 0; }
  50274. if (maximumScale === void 0) { maximumScale = 2; }
  50275. _super.call(this, priority);
  50276. this.priority = priority;
  50277. this.maximumScale = maximumScale;
  50278. this._currentScale = 1;
  50279. this.apply = function (scene) {
  50280. _this._currentScale++;
  50281. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  50282. return _this._currentScale >= _this.maximumScale;
  50283. };
  50284. }
  50285. return HardwareScalingOptimization;
  50286. })(SceneOptimization);
  50287. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  50288. var ShadowsOptimization = (function (_super) {
  50289. __extends(ShadowsOptimization, _super);
  50290. function ShadowsOptimization() {
  50291. _super.apply(this, arguments);
  50292. this.apply = function (scene) {
  50293. scene.shadowsEnabled = false;
  50294. return true;
  50295. };
  50296. }
  50297. return ShadowsOptimization;
  50298. })(SceneOptimization);
  50299. BABYLON.ShadowsOptimization = ShadowsOptimization;
  50300. var PostProcessesOptimization = (function (_super) {
  50301. __extends(PostProcessesOptimization, _super);
  50302. function PostProcessesOptimization() {
  50303. _super.apply(this, arguments);
  50304. this.apply = function (scene) {
  50305. scene.postProcessesEnabled = false;
  50306. return true;
  50307. };
  50308. }
  50309. return PostProcessesOptimization;
  50310. })(SceneOptimization);
  50311. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  50312. var LensFlaresOptimization = (function (_super) {
  50313. __extends(LensFlaresOptimization, _super);
  50314. function LensFlaresOptimization() {
  50315. _super.apply(this, arguments);
  50316. this.apply = function (scene) {
  50317. scene.lensFlaresEnabled = false;
  50318. return true;
  50319. };
  50320. }
  50321. return LensFlaresOptimization;
  50322. })(SceneOptimization);
  50323. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  50324. var ParticlesOptimization = (function (_super) {
  50325. __extends(ParticlesOptimization, _super);
  50326. function ParticlesOptimization() {
  50327. _super.apply(this, arguments);
  50328. this.apply = function (scene) {
  50329. scene.particlesEnabled = false;
  50330. return true;
  50331. };
  50332. }
  50333. return ParticlesOptimization;
  50334. })(SceneOptimization);
  50335. BABYLON.ParticlesOptimization = ParticlesOptimization;
  50336. var RenderTargetsOptimization = (function (_super) {
  50337. __extends(RenderTargetsOptimization, _super);
  50338. function RenderTargetsOptimization() {
  50339. _super.apply(this, arguments);
  50340. this.apply = function (scene) {
  50341. scene.renderTargetsEnabled = false;
  50342. return true;
  50343. };
  50344. }
  50345. return RenderTargetsOptimization;
  50346. })(SceneOptimization);
  50347. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  50348. var MergeMeshesOptimization = (function (_super) {
  50349. __extends(MergeMeshesOptimization, _super);
  50350. function MergeMeshesOptimization() {
  50351. var _this = this;
  50352. _super.apply(this, arguments);
  50353. this._canBeMerged = function (abstractMesh) {
  50354. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  50355. return false;
  50356. }
  50357. var mesh = abstractMesh;
  50358. if (!mesh.isVisible || !mesh.isEnabled()) {
  50359. return false;
  50360. }
  50361. if (mesh.instances.length > 0) {
  50362. return false;
  50363. }
  50364. if (mesh.skeleton || mesh.hasLODLevels) {
  50365. return false;
  50366. }
  50367. if (mesh.parent) {
  50368. return false;
  50369. }
  50370. return true;
  50371. };
  50372. this.apply = function (scene, updateSelectionTree) {
  50373. var globalPool = scene.meshes.slice(0);
  50374. var globalLength = globalPool.length;
  50375. for (var index = 0; index < globalLength; index++) {
  50376. var currentPool = new Array();
  50377. var current = globalPool[index];
  50378. // Checks
  50379. if (!_this._canBeMerged(current)) {
  50380. continue;
  50381. }
  50382. currentPool.push(current);
  50383. // Find compatible meshes
  50384. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  50385. var otherMesh = globalPool[subIndex];
  50386. if (!_this._canBeMerged(otherMesh)) {
  50387. continue;
  50388. }
  50389. if (otherMesh.material !== current.material) {
  50390. continue;
  50391. }
  50392. if (otherMesh.checkCollisions !== current.checkCollisions) {
  50393. continue;
  50394. }
  50395. currentPool.push(otherMesh);
  50396. globalLength--;
  50397. globalPool.splice(subIndex, 1);
  50398. subIndex--;
  50399. }
  50400. if (currentPool.length < 2) {
  50401. continue;
  50402. }
  50403. // Merge meshes
  50404. BABYLON.Mesh.MergeMeshes(currentPool);
  50405. }
  50406. if (updateSelectionTree != undefined) {
  50407. if (updateSelectionTree) {
  50408. scene.createOrUpdateSelectionOctree();
  50409. }
  50410. }
  50411. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  50412. scene.createOrUpdateSelectionOctree();
  50413. }
  50414. return true;
  50415. };
  50416. }
  50417. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  50418. get: function () {
  50419. return MergeMeshesOptimization._UpdateSelectionTree;
  50420. },
  50421. set: function (value) {
  50422. MergeMeshesOptimization._UpdateSelectionTree = value;
  50423. },
  50424. enumerable: true,
  50425. configurable: true
  50426. });
  50427. MergeMeshesOptimization._UpdateSelectionTree = false;
  50428. return MergeMeshesOptimization;
  50429. })(SceneOptimization);
  50430. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  50431. // Options
  50432. var SceneOptimizerOptions = (function () {
  50433. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  50434. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  50435. if (trackerDuration === void 0) { trackerDuration = 2000; }
  50436. this.targetFrameRate = targetFrameRate;
  50437. this.trackerDuration = trackerDuration;
  50438. this.optimizations = new Array();
  50439. }
  50440. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  50441. var result = new SceneOptimizerOptions(targetFrameRate);
  50442. var priority = 0;
  50443. result.optimizations.push(new MergeMeshesOptimization(priority));
  50444. result.optimizations.push(new ShadowsOptimization(priority));
  50445. result.optimizations.push(new LensFlaresOptimization(priority));
  50446. // Next priority
  50447. priority++;
  50448. result.optimizations.push(new PostProcessesOptimization(priority));
  50449. result.optimizations.push(new ParticlesOptimization(priority));
  50450. // Next priority
  50451. priority++;
  50452. result.optimizations.push(new TextureOptimization(priority, 1024));
  50453. return result;
  50454. };
  50455. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  50456. var result = new SceneOptimizerOptions(targetFrameRate);
  50457. var priority = 0;
  50458. result.optimizations.push(new MergeMeshesOptimization(priority));
  50459. result.optimizations.push(new ShadowsOptimization(priority));
  50460. result.optimizations.push(new LensFlaresOptimization(priority));
  50461. // Next priority
  50462. priority++;
  50463. result.optimizations.push(new PostProcessesOptimization(priority));
  50464. result.optimizations.push(new ParticlesOptimization(priority));
  50465. // Next priority
  50466. priority++;
  50467. result.optimizations.push(new TextureOptimization(priority, 512));
  50468. // Next priority
  50469. priority++;
  50470. result.optimizations.push(new RenderTargetsOptimization(priority));
  50471. // Next priority
  50472. priority++;
  50473. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  50474. return result;
  50475. };
  50476. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  50477. var result = new SceneOptimizerOptions(targetFrameRate);
  50478. var priority = 0;
  50479. result.optimizations.push(new MergeMeshesOptimization(priority));
  50480. result.optimizations.push(new ShadowsOptimization(priority));
  50481. result.optimizations.push(new LensFlaresOptimization(priority));
  50482. // Next priority
  50483. priority++;
  50484. result.optimizations.push(new PostProcessesOptimization(priority));
  50485. result.optimizations.push(new ParticlesOptimization(priority));
  50486. // Next priority
  50487. priority++;
  50488. result.optimizations.push(new TextureOptimization(priority, 256));
  50489. // Next priority
  50490. priority++;
  50491. result.optimizations.push(new RenderTargetsOptimization(priority));
  50492. // Next priority
  50493. priority++;
  50494. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  50495. return result;
  50496. };
  50497. return SceneOptimizerOptions;
  50498. })();
  50499. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  50500. // Scene optimizer tool
  50501. var SceneOptimizer = (function () {
  50502. function SceneOptimizer() {
  50503. }
  50504. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  50505. // TODO: add an epsilon
  50506. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  50507. if (onSuccess) {
  50508. onSuccess();
  50509. }
  50510. return;
  50511. }
  50512. // Apply current level of optimizations
  50513. var allDone = true;
  50514. var noOptimizationApplied = true;
  50515. for (var index = 0; index < options.optimizations.length; index++) {
  50516. var optimization = options.optimizations[index];
  50517. if (optimization.priority === currentPriorityLevel) {
  50518. noOptimizationApplied = false;
  50519. allDone = allDone && optimization.apply(scene);
  50520. }
  50521. }
  50522. // If no optimization was applied, this is a failure :(
  50523. if (noOptimizationApplied) {
  50524. if (onFailure) {
  50525. onFailure();
  50526. }
  50527. return;
  50528. }
  50529. // If all optimizations were done, move to next level
  50530. if (allDone) {
  50531. currentPriorityLevel++;
  50532. }
  50533. // Let's the system running for a specific amount of time before checking FPS
  50534. scene.executeWhenReady(function () {
  50535. setTimeout(function () {
  50536. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  50537. }, options.trackerDuration);
  50538. });
  50539. };
  50540. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  50541. if (!options) {
  50542. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  50543. }
  50544. // Let's the system running for a specific amount of time before checking FPS
  50545. scene.executeWhenReady(function () {
  50546. setTimeout(function () {
  50547. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  50548. }, options.trackerDuration);
  50549. });
  50550. };
  50551. return SceneOptimizer;
  50552. })();
  50553. BABYLON.SceneOptimizer = SceneOptimizer;
  50554. })(BABYLON || (BABYLON = {}));
  50555. var BABYLON;
  50556. (function (BABYLON) {
  50557. var Internals;
  50558. (function (Internals) {
  50559. var MeshLODLevel = (function () {
  50560. function MeshLODLevel(distance, mesh) {
  50561. this.distance = distance;
  50562. this.mesh = mesh;
  50563. }
  50564. return MeshLODLevel;
  50565. })();
  50566. Internals.MeshLODLevel = MeshLODLevel;
  50567. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50568. })(BABYLON || (BABYLON = {}));
  50569. var BABYLON;
  50570. (function (BABYLON) {
  50571. var RawTexture = (function (_super) {
  50572. __extends(RawTexture, _super);
  50573. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50575. if (invertY === void 0) { invertY = false; }
  50576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50577. _super.call(this, null, scene, !generateMipMaps, invertY);
  50578. this.format = format;
  50579. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50580. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50581. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50582. }
  50583. RawTexture.prototype.update = function (data) {
  50584. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  50585. };
  50586. // Statics
  50587. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50588. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50589. if (invertY === void 0) { invertY = false; }
  50590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50591. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50592. };
  50593. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50594. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50595. if (invertY === void 0) { invertY = false; }
  50596. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50597. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50598. };
  50599. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50600. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50601. if (invertY === void 0) { invertY = false; }
  50602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50603. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50604. };
  50605. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50606. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50607. if (invertY === void 0) { invertY = false; }
  50608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50609. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50610. };
  50611. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50613. if (invertY === void 0) { invertY = false; }
  50614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50615. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50616. };
  50617. return RawTexture;
  50618. })(BABYLON.Texture);
  50619. BABYLON.RawTexture = RawTexture;
  50620. })(BABYLON || (BABYLON = {}));
  50621. var BABYLON;
  50622. (function (BABYLON) {
  50623. var IndexedVector2 = (function (_super) {
  50624. __extends(IndexedVector2, _super);
  50625. function IndexedVector2(original, index) {
  50626. _super.call(this, original.x, original.y);
  50627. this.index = index;
  50628. }
  50629. return IndexedVector2;
  50630. })(BABYLON.Vector2);
  50631. var PolygonPoints = (function () {
  50632. function PolygonPoints() {
  50633. this.elements = new Array();
  50634. }
  50635. PolygonPoints.prototype.add = function (originalPoints) {
  50636. var _this = this;
  50637. var result = new Array();
  50638. originalPoints.forEach(function (point) {
  50639. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  50640. var newPoint = new IndexedVector2(point, _this.elements.length);
  50641. result.push(newPoint);
  50642. _this.elements.push(newPoint);
  50643. }
  50644. });
  50645. return result;
  50646. };
  50647. PolygonPoints.prototype.computeBounds = function () {
  50648. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  50649. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  50650. this.elements.forEach(function (point) {
  50651. // x
  50652. if (point.x < lmin.x) {
  50653. lmin.x = point.x;
  50654. }
  50655. else if (point.x > lmax.x) {
  50656. lmax.x = point.x;
  50657. }
  50658. // y
  50659. if (point.y < lmin.y) {
  50660. lmin.y = point.y;
  50661. }
  50662. else if (point.y > lmax.y) {
  50663. lmax.y = point.y;
  50664. }
  50665. });
  50666. return {
  50667. min: lmin,
  50668. max: lmax,
  50669. width: lmax.x - lmin.x,
  50670. height: lmax.y - lmin.y
  50671. };
  50672. };
  50673. return PolygonPoints;
  50674. })();
  50675. var Polygon = (function () {
  50676. function Polygon() {
  50677. }
  50678. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  50679. return [
  50680. new BABYLON.Vector2(xmin, ymin),
  50681. new BABYLON.Vector2(xmax, ymin),
  50682. new BABYLON.Vector2(xmax, ymax),
  50683. new BABYLON.Vector2(xmin, ymax)
  50684. ];
  50685. };
  50686. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  50687. if (cx === void 0) { cx = 0; }
  50688. if (cy === void 0) { cy = 0; }
  50689. if (numberOfSides === void 0) { numberOfSides = 32; }
  50690. var result = new Array();
  50691. var angle = 0;
  50692. var increment = (Math.PI * 2) / numberOfSides;
  50693. for (var i = 0; i < numberOfSides; i++) {
  50694. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  50695. angle -= increment;
  50696. }
  50697. return result;
  50698. };
  50699. Polygon.Parse = function (input) {
  50700. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  50701. var i, result = [];
  50702. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  50703. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  50704. }
  50705. return result;
  50706. };
  50707. Polygon.StartingAt = function (x, y) {
  50708. return BABYLON.Path2.StartingAt(x, y);
  50709. };
  50710. return Polygon;
  50711. })();
  50712. BABYLON.Polygon = Polygon;
  50713. var PolygonMeshBuilder = (function () {
  50714. function PolygonMeshBuilder(name, contours, scene) {
  50715. this._points = new PolygonPoints();
  50716. this._outlinepoints = new PolygonPoints();
  50717. this._holes = [];
  50718. this._epoints = new Array();
  50719. this._eholes = new Array();
  50720. this._name = name;
  50721. this._scene = scene;
  50722. var points;
  50723. if (contours instanceof BABYLON.Path2) {
  50724. points = contours.getPoints();
  50725. }
  50726. else {
  50727. points = contours;
  50728. }
  50729. this._addToepoint(points);
  50730. this._points.add(points);
  50731. this._outlinepoints.add(points);
  50732. }
  50733. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  50734. for (var _i = 0; _i < points.length; _i++) {
  50735. var p = points[_i];
  50736. this._epoints.push(p.x, p.y);
  50737. }
  50738. };
  50739. PolygonMeshBuilder.prototype.addHole = function (hole) {
  50740. this._points.add(hole);
  50741. var holepoints = new PolygonPoints();
  50742. holepoints.add(hole);
  50743. this._holes.push(holepoints);
  50744. this._eholes.push(this._epoints.length / 2);
  50745. this._addToepoint(hole);
  50746. return this;
  50747. };
  50748. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  50749. var _this = this;
  50750. if (updatable === void 0) { updatable = false; }
  50751. var result = new BABYLON.Mesh(this._name, this._scene);
  50752. var normals = [];
  50753. var positions = [];
  50754. var uvs = [];
  50755. var bounds = this._points.computeBounds();
  50756. this._points.elements.forEach(function (p) {
  50757. normals.push(0, 1.0, 0);
  50758. positions.push(p.x, 0, p.y);
  50759. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  50760. });
  50761. var indices = [];
  50762. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  50763. for (var i = 0; i < res.length; i++) {
  50764. indices.push(res[i]);
  50765. }
  50766. if (depth > 0) {
  50767. var positionscount = (positions.length / 3); //get the current pointcount
  50768. this._points.elements.forEach(function (p) {
  50769. normals.push(0, -1.0, 0);
  50770. positions.push(p.x, -depth, p.y);
  50771. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  50772. });
  50773. var totalCount = indices.length;
  50774. for (var i = 0; i < totalCount; i += 3) {
  50775. var i0 = indices[i + 0];
  50776. var i1 = indices[i + 1];
  50777. var i2 = indices[i + 2];
  50778. indices.push(i2 + positionscount);
  50779. indices.push(i1 + positionscount);
  50780. indices.push(i0 + positionscount);
  50781. }
  50782. //Add the sides
  50783. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  50784. this._holes.forEach(function (hole) {
  50785. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  50786. });
  50787. }
  50788. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  50789. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  50790. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  50791. result.setIndices(indices);
  50792. return result;
  50793. };
  50794. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  50795. var StartIndex = positions.length / 3;
  50796. var ulength = 0;
  50797. for (var i = 0; i < points.elements.length; i++) {
  50798. var p = points.elements[i];
  50799. var p1;
  50800. if ((i + 1) > points.elements.length - 1) {
  50801. p1 = points.elements[0];
  50802. }
  50803. else {
  50804. p1 = points.elements[i + 1];
  50805. }
  50806. positions.push(p.x, 0, p.y);
  50807. positions.push(p.x, -depth, p.y);
  50808. positions.push(p1.x, 0, p1.y);
  50809. positions.push(p1.x, -depth, p1.y);
  50810. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  50811. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  50812. var v3 = v2.subtract(v1);
  50813. var v4 = new BABYLON.Vector3(0, 1, 0);
  50814. var vn = BABYLON.Vector3.Cross(v3, v4);
  50815. vn = vn.normalize();
  50816. uvs.push(ulength / bounds.width, 0);
  50817. uvs.push(ulength / bounds.width, 1);
  50818. ulength += v3.length();
  50819. uvs.push((ulength / bounds.width), 0);
  50820. uvs.push((ulength / bounds.width), 1);
  50821. if (!flip) {
  50822. normals.push(-vn.x, -vn.y, -vn.z);
  50823. normals.push(-vn.x, -vn.y, -vn.z);
  50824. normals.push(-vn.x, -vn.y, -vn.z);
  50825. normals.push(-vn.x, -vn.y, -vn.z);
  50826. indices.push(StartIndex);
  50827. indices.push(StartIndex + 1);
  50828. indices.push(StartIndex + 2);
  50829. indices.push(StartIndex + 1);
  50830. indices.push(StartIndex + 3);
  50831. indices.push(StartIndex + 2);
  50832. }
  50833. else {
  50834. normals.push(vn.x, vn.y, vn.z);
  50835. normals.push(vn.x, vn.y, vn.z);
  50836. normals.push(vn.x, vn.y, vn.z);
  50837. normals.push(vn.x, vn.y, vn.z);
  50838. indices.push(StartIndex);
  50839. indices.push(StartIndex + 2);
  50840. indices.push(StartIndex + 1);
  50841. indices.push(StartIndex + 1);
  50842. indices.push(StartIndex + 2);
  50843. indices.push(StartIndex + 3);
  50844. }
  50845. StartIndex += 4;
  50846. }
  50847. ;
  50848. };
  50849. return PolygonMeshBuilder;
  50850. })();
  50851. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50852. })(BABYLON || (BABYLON = {}));
  50853. var BABYLON;
  50854. (function (BABYLON) {
  50855. var Octree = (function () {
  50856. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50857. if (maxDepth === void 0) { maxDepth = 2; }
  50858. this.maxDepth = maxDepth;
  50859. this.dynamicContent = new Array();
  50860. this._maxBlockCapacity = maxBlockCapacity || 64;
  50861. this._selectionContent = new BABYLON.SmartArray(1024);
  50862. this._creationFunc = creationFunc;
  50863. }
  50864. // Methods
  50865. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50866. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50867. };
  50868. Octree.prototype.addMesh = function (entry) {
  50869. for (var index = 0; index < this.blocks.length; index++) {
  50870. var block = this.blocks[index];
  50871. block.addEntry(entry);
  50872. }
  50873. };
  50874. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50875. this._selectionContent.reset();
  50876. for (var index = 0; index < this.blocks.length; index++) {
  50877. var block = this.blocks[index];
  50878. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50879. }
  50880. if (allowDuplicate) {
  50881. this._selectionContent.concat(this.dynamicContent);
  50882. }
  50883. else {
  50884. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50885. }
  50886. return this._selectionContent;
  50887. };
  50888. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50889. this._selectionContent.reset();
  50890. for (var index = 0; index < this.blocks.length; index++) {
  50891. var block = this.blocks[index];
  50892. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50893. }
  50894. if (allowDuplicate) {
  50895. this._selectionContent.concat(this.dynamicContent);
  50896. }
  50897. else {
  50898. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50899. }
  50900. return this._selectionContent;
  50901. };
  50902. Octree.prototype.intersectsRay = function (ray) {
  50903. this._selectionContent.reset();
  50904. for (var index = 0; index < this.blocks.length; index++) {
  50905. var block = this.blocks[index];
  50906. block.intersectsRay(ray, this._selectionContent);
  50907. }
  50908. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50909. return this._selectionContent;
  50910. };
  50911. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50912. target.blocks = new Array();
  50913. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50914. // Segmenting space
  50915. for (var x = 0; x < 2; x++) {
  50916. for (var y = 0; y < 2; y++) {
  50917. for (var z = 0; z < 2; z++) {
  50918. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50919. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50920. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50921. block.addEntries(entries);
  50922. target.blocks.push(block);
  50923. }
  50924. }
  50925. }
  50926. };
  50927. Octree.CreationFuncForMeshes = function (entry, block) {
  50928. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50929. block.entries.push(entry);
  50930. }
  50931. };
  50932. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50933. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50934. block.entries.push(entry);
  50935. }
  50936. };
  50937. return Octree;
  50938. })();
  50939. BABYLON.Octree = Octree;
  50940. })(BABYLON || (BABYLON = {}));
  50941. var BABYLON;
  50942. (function (BABYLON) {
  50943. var OctreeBlock = (function () {
  50944. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50945. this.entries = new Array();
  50946. this._boundingVectors = new Array();
  50947. this._capacity = capacity;
  50948. this._depth = depth;
  50949. this._maxDepth = maxDepth;
  50950. this._creationFunc = creationFunc;
  50951. this._minPoint = minPoint;
  50952. this._maxPoint = maxPoint;
  50953. this._boundingVectors.push(minPoint.clone());
  50954. this._boundingVectors.push(maxPoint.clone());
  50955. this._boundingVectors.push(minPoint.clone());
  50956. this._boundingVectors[2].x = maxPoint.x;
  50957. this._boundingVectors.push(minPoint.clone());
  50958. this._boundingVectors[3].y = maxPoint.y;
  50959. this._boundingVectors.push(minPoint.clone());
  50960. this._boundingVectors[4].z = maxPoint.z;
  50961. this._boundingVectors.push(maxPoint.clone());
  50962. this._boundingVectors[5].z = minPoint.z;
  50963. this._boundingVectors.push(maxPoint.clone());
  50964. this._boundingVectors[6].x = minPoint.x;
  50965. this._boundingVectors.push(maxPoint.clone());
  50966. this._boundingVectors[7].y = minPoint.y;
  50967. }
  50968. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50969. // Property
  50970. get: function () {
  50971. return this._capacity;
  50972. },
  50973. enumerable: true,
  50974. configurable: true
  50975. });
  50976. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50977. get: function () {
  50978. return this._minPoint;
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50984. get: function () {
  50985. return this._maxPoint;
  50986. },
  50987. enumerable: true,
  50988. configurable: true
  50989. });
  50990. // Methods
  50991. OctreeBlock.prototype.addEntry = function (entry) {
  50992. if (this.blocks) {
  50993. for (var index = 0; index < this.blocks.length; index++) {
  50994. var block = this.blocks[index];
  50995. block.addEntry(entry);
  50996. }
  50997. return;
  50998. }
  50999. this._creationFunc(entry, this);
  51000. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  51001. this.createInnerBlocks();
  51002. }
  51003. };
  51004. OctreeBlock.prototype.addEntries = function (entries) {
  51005. for (var index = 0; index < entries.length; index++) {
  51006. var mesh = entries[index];
  51007. this.addEntry(mesh);
  51008. }
  51009. };
  51010. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  51011. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  51012. if (this.blocks) {
  51013. for (var index = 0; index < this.blocks.length; index++) {
  51014. var block = this.blocks[index];
  51015. block.select(frustumPlanes, selection, allowDuplicate);
  51016. }
  51017. return;
  51018. }
  51019. if (allowDuplicate) {
  51020. selection.concat(this.entries);
  51021. }
  51022. else {
  51023. selection.concatWithNoDuplicate(this.entries);
  51024. }
  51025. }
  51026. };
  51027. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  51028. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  51029. if (this.blocks) {
  51030. for (var index = 0; index < this.blocks.length; index++) {
  51031. var block = this.blocks[index];
  51032. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  51033. }
  51034. return;
  51035. }
  51036. if (allowDuplicate) {
  51037. selection.concat(this.entries);
  51038. }
  51039. else {
  51040. selection.concatWithNoDuplicate(this.entries);
  51041. }
  51042. }
  51043. };
  51044. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  51045. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  51046. if (this.blocks) {
  51047. for (var index = 0; index < this.blocks.length; index++) {
  51048. var block = this.blocks[index];
  51049. block.intersectsRay(ray, selection);
  51050. }
  51051. return;
  51052. }
  51053. selection.concatWithNoDuplicate(this.entries);
  51054. }
  51055. };
  51056. OctreeBlock.prototype.createInnerBlocks = function () {
  51057. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  51058. };
  51059. return OctreeBlock;
  51060. })();
  51061. BABYLON.OctreeBlock = OctreeBlock;
  51062. })(BABYLON || (BABYLON = {}));
  51063. var BABYLON;
  51064. (function (BABYLON) {
  51065. var BlurPostProcess = (function (_super) {
  51066. __extends(BlurPostProcess, _super);
  51067. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  51068. var _this = this;
  51069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51070. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  51071. this.direction = direction;
  51072. this.blurWidth = blurWidth;
  51073. this.onApplyObservable.add(function (effect) {
  51074. effect.setFloat2("screenSize", _this.width, _this.height);
  51075. effect.setVector2("direction", _this.direction);
  51076. effect.setFloat("blurWidth", _this.blurWidth);
  51077. });
  51078. }
  51079. return BlurPostProcess;
  51080. })(BABYLON.PostProcess);
  51081. BABYLON.BlurPostProcess = BlurPostProcess;
  51082. })(BABYLON || (BABYLON = {}));
  51083. var BABYLON;
  51084. (function (BABYLON) {
  51085. var RefractionPostProcess = (function (_super) {
  51086. __extends(RefractionPostProcess, _super);
  51087. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51088. var _this = this;
  51089. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  51090. this.color = color;
  51091. this.depth = depth;
  51092. this.colorLevel = colorLevel;
  51093. this.onActivateObservable.add(function (cam) {
  51094. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51095. });
  51096. this.onApplyObservable.add(function (effect) {
  51097. effect.setColor3("baseColor", _this.color);
  51098. effect.setFloat("depth", _this.depth);
  51099. effect.setFloat("colorLevel", _this.colorLevel);
  51100. effect.setTexture("refractionSampler", _this._refRexture);
  51101. });
  51102. }
  51103. // Methods
  51104. RefractionPostProcess.prototype.dispose = function (camera) {
  51105. if (this._refRexture) {
  51106. this._refRexture.dispose();
  51107. }
  51108. _super.prototype.dispose.call(this, camera);
  51109. };
  51110. return RefractionPostProcess;
  51111. })(BABYLON.PostProcess);
  51112. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51113. })(BABYLON || (BABYLON = {}));
  51114. var BABYLON;
  51115. (function (BABYLON) {
  51116. var BlackAndWhitePostProcess = (function (_super) {
  51117. __extends(BlackAndWhitePostProcess, _super);
  51118. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51119. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  51120. }
  51121. return BlackAndWhitePostProcess;
  51122. })(BABYLON.PostProcess);
  51123. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51124. })(BABYLON || (BABYLON = {}));
  51125. var BABYLON;
  51126. (function (BABYLON) {
  51127. var ConvolutionPostProcess = (function (_super) {
  51128. __extends(ConvolutionPostProcess, _super);
  51129. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51130. var _this = this;
  51131. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  51132. this.kernel = kernel;
  51133. this.onApply = function (effect) {
  51134. effect.setFloat2("screenSize", _this.width, _this.height);
  51135. effect.setArray("kernel", _this.kernel);
  51136. };
  51137. }
  51138. // Statics
  51139. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51140. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51141. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51142. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51143. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51144. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51145. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51146. return ConvolutionPostProcess;
  51147. })(BABYLON.PostProcess);
  51148. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51149. })(BABYLON || (BABYLON = {}));
  51150. var BABYLON;
  51151. (function (BABYLON) {
  51152. var FilterPostProcess = (function (_super) {
  51153. __extends(FilterPostProcess, _super);
  51154. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51155. var _this = this;
  51156. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  51157. this.kernelMatrix = kernelMatrix;
  51158. this.onApply = function (effect) {
  51159. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51160. };
  51161. }
  51162. return FilterPostProcess;
  51163. })(BABYLON.PostProcess);
  51164. BABYLON.FilterPostProcess = FilterPostProcess;
  51165. })(BABYLON || (BABYLON = {}));
  51166. var BABYLON;
  51167. (function (BABYLON) {
  51168. var FxaaPostProcess = (function (_super) {
  51169. __extends(FxaaPostProcess, _super);
  51170. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  51171. var _this = this;
  51172. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  51173. this.onSizeChangedObservable.add(function () {
  51174. _this.texelWidth = 1.0 / _this.width;
  51175. _this.texelHeight = 1.0 / _this.height;
  51176. });
  51177. this.onApplyObservable.add(function (effect) {
  51178. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  51179. });
  51180. }
  51181. return FxaaPostProcess;
  51182. })(BABYLON.PostProcess);
  51183. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51184. })(BABYLON || (BABYLON = {}));
  51185. var BABYLON;
  51186. (function (BABYLON) {
  51187. var StereoscopicInterlacePostProcess = (function (_super) {
  51188. __extends(StereoscopicInterlacePostProcess, _super);
  51189. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  51190. var _this = this;
  51191. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  51192. this._passedProcess = rigCameras[0]._rigPostProcess;
  51193. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  51194. this.onSizeChangedObservable.add(function () {
  51195. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  51196. });
  51197. this.onApplyObservable.add(function (effect) {
  51198. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  51199. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  51200. });
  51201. }
  51202. return StereoscopicInterlacePostProcess;
  51203. })(BABYLON.PostProcess);
  51204. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  51205. })(BABYLON || (BABYLON = {}));
  51206. var BABYLON;
  51207. (function (BABYLON) {
  51208. var LensFlare = (function () {
  51209. function LensFlare(size, position, color, imgUrl, system) {
  51210. this.size = size;
  51211. this.position = position;
  51212. this.dispose = function () {
  51213. if (this.texture) {
  51214. this.texture.dispose();
  51215. }
  51216. // Remove from scene
  51217. var index = this._system.lensFlares.indexOf(this);
  51218. this._system.lensFlares.splice(index, 1);
  51219. };
  51220. this.color = color || new BABYLON.Color3(1, 1, 1);
  51221. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  51222. this._system = system;
  51223. system.lensFlares.push(this);
  51224. }
  51225. return LensFlare;
  51226. })();
  51227. BABYLON.LensFlare = LensFlare;
  51228. })(BABYLON || (BABYLON = {}));
  51229. var BABYLON;
  51230. (function (BABYLON) {
  51231. var LensFlareSystem = (function () {
  51232. function LensFlareSystem(name, emitter, scene) {
  51233. this.name = name;
  51234. this.lensFlares = new Array();
  51235. this.borderLimit = 300;
  51236. this.layerMask = 0x0FFFFFFF;
  51237. this._vertexBuffers = {};
  51238. this._isEnabled = true;
  51239. this._scene = scene;
  51240. this._emitter = emitter;
  51241. this.id = name;
  51242. scene.lensFlareSystems.push(this);
  51243. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  51244. var engine = scene.getEngine();
  51245. // VBO
  51246. var vertices = [];
  51247. vertices.push(1, 1);
  51248. vertices.push(-1, 1);
  51249. vertices.push(-1, -1);
  51250. vertices.push(1, -1);
  51251. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  51252. // Indices
  51253. var indices = [];
  51254. indices.push(0);
  51255. indices.push(1);
  51256. indices.push(2);
  51257. indices.push(0);
  51258. indices.push(2);
  51259. indices.push(3);
  51260. this._indexBuffer = engine.createIndexBuffer(indices);
  51261. // Effects
  51262. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  51263. }
  51264. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  51265. get: function () {
  51266. return this._isEnabled;
  51267. },
  51268. set: function (value) {
  51269. this._isEnabled = value;
  51270. },
  51271. enumerable: true,
  51272. configurable: true
  51273. });
  51274. LensFlareSystem.prototype.getScene = function () {
  51275. return this._scene;
  51276. };
  51277. LensFlareSystem.prototype.getEmitter = function () {
  51278. return this._emitter;
  51279. };
  51280. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  51281. this._emitter = newEmitter;
  51282. };
  51283. LensFlareSystem.prototype.getEmitterPosition = function () {
  51284. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  51285. };
  51286. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  51287. var position = this.getEmitterPosition();
  51288. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  51289. this._positionX = position.x;
  51290. this._positionY = position.y;
  51291. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  51292. if (position.z > 0) {
  51293. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  51294. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  51295. return true;
  51296. }
  51297. }
  51298. return false;
  51299. };
  51300. LensFlareSystem.prototype._isVisible = function () {
  51301. if (!this._isEnabled) {
  51302. return false;
  51303. }
  51304. var emitterPosition = this.getEmitterPosition();
  51305. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  51306. var distance = direction.length();
  51307. direction.normalize();
  51308. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  51309. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  51310. return !pickInfo.hit || pickInfo.distance > distance;
  51311. };
  51312. LensFlareSystem.prototype.render = function () {
  51313. if (!this._effect.isReady())
  51314. return false;
  51315. var engine = this._scene.getEngine();
  51316. var viewport = this._scene.activeCamera.viewport;
  51317. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  51318. // Position
  51319. if (!this.computeEffectivePosition(globalViewport)) {
  51320. return false;
  51321. }
  51322. // Visibility
  51323. if (!this._isVisible()) {
  51324. return false;
  51325. }
  51326. // Intensity
  51327. var awayX;
  51328. var awayY;
  51329. if (this._positionX < this.borderLimit + globalViewport.x) {
  51330. awayX = this.borderLimit + globalViewport.x - this._positionX;
  51331. }
  51332. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  51333. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  51334. }
  51335. else {
  51336. awayX = 0;
  51337. }
  51338. if (this._positionY < this.borderLimit + globalViewport.y) {
  51339. awayY = this.borderLimit + globalViewport.y - this._positionY;
  51340. }
  51341. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  51342. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  51343. }
  51344. else {
  51345. awayY = 0;
  51346. }
  51347. var away = (awayX > awayY) ? awayX : awayY;
  51348. if (away > this.borderLimit) {
  51349. away = this.borderLimit;
  51350. }
  51351. var intensity = 1.0 - (away / this.borderLimit);
  51352. if (intensity < 0) {
  51353. return false;
  51354. }
  51355. if (intensity > 1.0) {
  51356. intensity = 1.0;
  51357. }
  51358. // Position
  51359. var centerX = globalViewport.x + globalViewport.width / 2;
  51360. var centerY = globalViewport.y + globalViewport.height / 2;
  51361. var distX = centerX - this._positionX;
  51362. var distY = centerY - this._positionY;
  51363. // Effects
  51364. engine.enableEffect(this._effect);
  51365. engine.setState(false);
  51366. engine.setDepthBuffer(false);
  51367. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51368. // VBOs
  51369. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51370. // Flares
  51371. for (var index = 0; index < this.lensFlares.length; index++) {
  51372. var flare = this.lensFlares[index];
  51373. var x = centerX - (distX * flare.position);
  51374. var y = centerY - (distY * flare.position);
  51375. var cw = flare.size;
  51376. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  51377. var cx = 2 * (x / globalViewport.width) - 1.0;
  51378. var cy = 1.0 - 2 * (y / globalViewport.height);
  51379. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  51380. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  51381. // Texture
  51382. this._effect.setTexture("textureSampler", flare.texture);
  51383. // Color
  51384. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  51385. // Draw order
  51386. engine.draw(true, 0, 6);
  51387. }
  51388. engine.setDepthBuffer(true);
  51389. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51390. return true;
  51391. };
  51392. LensFlareSystem.prototype.dispose = function () {
  51393. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  51394. if (vertexBuffer) {
  51395. vertexBuffer.dispose();
  51396. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  51397. }
  51398. if (this._indexBuffer) {
  51399. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51400. this._indexBuffer = null;
  51401. }
  51402. while (this.lensFlares.length) {
  51403. this.lensFlares[0].dispose();
  51404. }
  51405. // Remove from scene
  51406. var index = this._scene.lensFlareSystems.indexOf(this);
  51407. this._scene.lensFlareSystems.splice(index, 1);
  51408. };
  51409. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  51410. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  51411. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  51412. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  51413. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  51414. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  51415. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  51416. var parsedFlare = parsedLensFlareSystem.flares[index];
  51417. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  51418. }
  51419. return lensFlareSystem;
  51420. };
  51421. LensFlareSystem.prototype.serialize = function () {
  51422. var serializationObject = {};
  51423. serializationObject.id = this.id;
  51424. serializationObject.name = this.name;
  51425. serializationObject.emitterId = this.getEmitter().id;
  51426. serializationObject.borderLimit = this.borderLimit;
  51427. serializationObject.flares = [];
  51428. for (var index = 0; index < this.lensFlares.length; index++) {
  51429. var flare = this.lensFlares[index];
  51430. serializationObject.flares.push({
  51431. size: flare.size,
  51432. position: flare.position,
  51433. color: flare.color.asArray(),
  51434. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  51435. });
  51436. }
  51437. return serializationObject;
  51438. };
  51439. return LensFlareSystem;
  51440. })();
  51441. BABYLON.LensFlareSystem = LensFlareSystem;
  51442. })(BABYLON || (BABYLON = {}));
  51443. var BABYLON;
  51444. (function (BABYLON) {
  51445. // We're mainly based on the logic defined into the FreeCamera code
  51446. var DeviceOrientationCamera = (function (_super) {
  51447. __extends(DeviceOrientationCamera, _super);
  51448. //-- end properties for backward compatibility for inputs
  51449. function DeviceOrientationCamera(name, position, scene) {
  51450. _super.call(this, name, position, scene);
  51451. this.inputs.addDeviceOrientation();
  51452. }
  51453. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  51454. //-- Begin properties for backward compatibility for inputs
  51455. get: function () {
  51456. return 0;
  51457. },
  51458. set: function (value) {
  51459. },
  51460. enumerable: true,
  51461. configurable: true
  51462. });
  51463. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  51464. get: function () {
  51465. return 0;
  51466. },
  51467. set: function (value) {
  51468. },
  51469. enumerable: true,
  51470. configurable: true
  51471. });
  51472. DeviceOrientationCamera.prototype.getTypeName = function () {
  51473. return "DeviceOrientationCamera";
  51474. };
  51475. return DeviceOrientationCamera;
  51476. })(BABYLON.FreeCamera);
  51477. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  51478. })(BABYLON || (BABYLON = {}));
  51479. var BABYLON;
  51480. (function (BABYLON) {
  51481. // We're mainly based on the logic defined into the FreeCamera code
  51482. var UniversalCamera = (function (_super) {
  51483. __extends(UniversalCamera, _super);
  51484. //-- end properties for backward compatibility for inputs
  51485. function UniversalCamera(name, position, scene) {
  51486. _super.call(this, name, position, scene);
  51487. this.inputs.addGamepad();
  51488. }
  51489. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51490. //-- Begin properties for backward compatibility for inputs
  51491. get: function () {
  51492. var gamepad = this.inputs.attached["gamepad"];
  51493. if (gamepad)
  51494. return gamepad.gamepadAngularSensibility;
  51495. },
  51496. set: function (value) {
  51497. var gamepad = this.inputs.attached["gamepad"];
  51498. if (gamepad)
  51499. gamepad.gamepadAngularSensibility = value;
  51500. },
  51501. enumerable: true,
  51502. configurable: true
  51503. });
  51504. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51505. get: function () {
  51506. var gamepad = this.inputs.attached["gamepad"];
  51507. if (gamepad)
  51508. return gamepad.gamepadMoveSensibility;
  51509. },
  51510. set: function (value) {
  51511. var gamepad = this.inputs.attached["gamepad"];
  51512. if (gamepad)
  51513. gamepad.gamepadMoveSensibility = value;
  51514. },
  51515. enumerable: true,
  51516. configurable: true
  51517. });
  51518. UniversalCamera.prototype.getTypeName = function () {
  51519. return "UniversalCamera";
  51520. };
  51521. return UniversalCamera;
  51522. })(BABYLON.TouchCamera);
  51523. BABYLON.UniversalCamera = UniversalCamera;
  51524. })(BABYLON || (BABYLON = {}));
  51525. var BABYLON;
  51526. (function (BABYLON) {
  51527. var Gamepads = (function () {
  51528. function Gamepads(ongamedpadconnected) {
  51529. var _this = this;
  51530. this.babylonGamepads = [];
  51531. this.oneGamepadConnected = false;
  51532. this.isMonitoring = false;
  51533. this.gamepadEventSupported = 'GamepadEvent' in window;
  51534. this.gamepadSupportAvailable = (navigator.getGamepads ||
  51535. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  51536. this._callbackGamepadConnected = ongamedpadconnected;
  51537. if (this.gamepadSupportAvailable) {
  51538. // Checking if the gamepad connected event is supported (like in Firefox)
  51539. if (this.gamepadEventSupported) {
  51540. this._onGamepadConnectedEvent = function (evt) {
  51541. _this._onGamepadConnected(evt);
  51542. };
  51543. this._onGamepadDisonnectedEvent = function (evt) {
  51544. _this._onGamepadDisconnected(evt);
  51545. };
  51546. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51547. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  51548. }
  51549. else {
  51550. this._startMonitoringGamepads();
  51551. }
  51552. }
  51553. }
  51554. Gamepads.prototype.dispose = function () {
  51555. if (Gamepads.gamepadDOMInfo) {
  51556. document.body.removeChild(Gamepads.gamepadDOMInfo);
  51557. }
  51558. if (this._onGamepadConnectedEvent) {
  51559. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51560. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  51561. this._onGamepadConnectedEvent = null;
  51562. this._onGamepadDisonnectedEvent = null;
  51563. }
  51564. };
  51565. Gamepads.prototype._onGamepadConnected = function (evt) {
  51566. var newGamepad = this._addNewGamepad(evt.gamepad);
  51567. if (this._callbackGamepadConnected)
  51568. this._callbackGamepadConnected(newGamepad);
  51569. this._startMonitoringGamepads();
  51570. };
  51571. Gamepads.prototype._addNewGamepad = function (gamepad) {
  51572. if (!this.oneGamepadConnected) {
  51573. this.oneGamepadConnected = true;
  51574. if (Gamepads.gamepadDOMInfo) {
  51575. document.body.removeChild(Gamepads.gamepadDOMInfo);
  51576. Gamepads.gamepadDOMInfo = null;
  51577. }
  51578. }
  51579. var newGamepad;
  51580. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51581. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  51582. }
  51583. else {
  51584. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  51585. }
  51586. this.babylonGamepads.push(newGamepad);
  51587. return newGamepad;
  51588. };
  51589. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  51590. // Remove the gamepad from the list of gamepads to monitor.
  51591. for (var i in this.babylonGamepads) {
  51592. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  51593. this.babylonGamepads.splice(+i, 1);
  51594. break;
  51595. }
  51596. }
  51597. // If no gamepads are left, stop the polling loop.
  51598. if (this.babylonGamepads.length == 0) {
  51599. this._stopMonitoringGamepads();
  51600. }
  51601. };
  51602. Gamepads.prototype._startMonitoringGamepads = function () {
  51603. if (!this.isMonitoring) {
  51604. this.isMonitoring = true;
  51605. this._checkGamepadsStatus();
  51606. }
  51607. };
  51608. Gamepads.prototype._stopMonitoringGamepads = function () {
  51609. this.isMonitoring = false;
  51610. };
  51611. Gamepads.prototype._checkGamepadsStatus = function () {
  51612. var _this = this;
  51613. // updating gamepad objects
  51614. this._updateGamepadObjects();
  51615. for (var i in this.babylonGamepads) {
  51616. this.babylonGamepads[i].update();
  51617. }
  51618. if (this.isMonitoring) {
  51619. if (window.requestAnimationFrame) {
  51620. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51621. }
  51622. else if (window.mozRequestAnimationFrame) {
  51623. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51624. }
  51625. else if (window.webkitRequestAnimationFrame) {
  51626. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51627. }
  51628. }
  51629. };
  51630. // This function is called only on Chrome, which does not yet support
  51631. // connection/disconnection events, but requires you to monitor
  51632. // an array for changes.
  51633. Gamepads.prototype._updateGamepadObjects = function () {
  51634. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51635. for (var i = 0; i < gamepads.length; i++) {
  51636. if (gamepads[i]) {
  51637. if (!(gamepads[i].index in this.babylonGamepads)) {
  51638. var newGamepad = this._addNewGamepad(gamepads[i]);
  51639. if (this._callbackGamepadConnected) {
  51640. this._callbackGamepadConnected(newGamepad);
  51641. }
  51642. }
  51643. else {
  51644. this.babylonGamepads[i].browserGamepad = gamepads[i];
  51645. }
  51646. }
  51647. }
  51648. };
  51649. return Gamepads;
  51650. })();
  51651. BABYLON.Gamepads = Gamepads;
  51652. var StickValues = (function () {
  51653. function StickValues(x, y) {
  51654. this.x = x;
  51655. this.y = y;
  51656. }
  51657. return StickValues;
  51658. })();
  51659. BABYLON.StickValues = StickValues;
  51660. var Gamepad = (function () {
  51661. function Gamepad(id, index, browserGamepad) {
  51662. this.id = id;
  51663. this.index = index;
  51664. this.browserGamepad = browserGamepad;
  51665. if (this.browserGamepad.axes.length >= 2) {
  51666. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  51667. }
  51668. if (this.browserGamepad.axes.length >= 4) {
  51669. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  51670. }
  51671. }
  51672. Gamepad.prototype.onleftstickchanged = function (callback) {
  51673. this._onleftstickchanged = callback;
  51674. };
  51675. Gamepad.prototype.onrightstickchanged = function (callback) {
  51676. this._onrightstickchanged = callback;
  51677. };
  51678. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51679. get: function () {
  51680. return this._leftStick;
  51681. },
  51682. set: function (newValues) {
  51683. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51684. this._onleftstickchanged(newValues);
  51685. }
  51686. this._leftStick = newValues;
  51687. },
  51688. enumerable: true,
  51689. configurable: true
  51690. });
  51691. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51692. get: function () {
  51693. return this._rightStick;
  51694. },
  51695. set: function (newValues) {
  51696. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51697. this._onrightstickchanged(newValues);
  51698. }
  51699. this._rightStick = newValues;
  51700. },
  51701. enumerable: true,
  51702. configurable: true
  51703. });
  51704. Gamepad.prototype.update = function () {
  51705. if (this._leftStick) {
  51706. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  51707. }
  51708. if (this._rightStick) {
  51709. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  51710. }
  51711. };
  51712. return Gamepad;
  51713. })();
  51714. BABYLON.Gamepad = Gamepad;
  51715. var GenericPad = (function (_super) {
  51716. __extends(GenericPad, _super);
  51717. function GenericPad(id, index, gamepad) {
  51718. _super.call(this, id, index, gamepad);
  51719. this.id = id;
  51720. this.index = index;
  51721. this.gamepad = gamepad;
  51722. this._buttons = new Array(gamepad.buttons.length);
  51723. }
  51724. GenericPad.prototype.onbuttondown = function (callback) {
  51725. this._onbuttondown = callback;
  51726. };
  51727. GenericPad.prototype.onbuttonup = function (callback) {
  51728. this._onbuttonup = callback;
  51729. };
  51730. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51731. if (newValue !== currentValue) {
  51732. if (this._onbuttondown && newValue === 1) {
  51733. this._onbuttondown(buttonIndex);
  51734. }
  51735. if (this._onbuttonup && newValue === 0) {
  51736. this._onbuttonup(buttonIndex);
  51737. }
  51738. }
  51739. return newValue;
  51740. };
  51741. GenericPad.prototype.update = function () {
  51742. _super.prototype.update.call(this);
  51743. for (var index = 0; index < this._buttons.length; index++) {
  51744. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51745. }
  51746. };
  51747. return GenericPad;
  51748. })(Gamepad);
  51749. BABYLON.GenericPad = GenericPad;
  51750. (function (Xbox360Button) {
  51751. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51752. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51753. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51754. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51755. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51756. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51757. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51758. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51759. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51760. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51761. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51762. var Xbox360Button = BABYLON.Xbox360Button;
  51763. (function (Xbox360Dpad) {
  51764. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51765. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51766. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51767. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51768. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51769. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  51770. var Xbox360Pad = (function (_super) {
  51771. __extends(Xbox360Pad, _super);
  51772. function Xbox360Pad() {
  51773. _super.apply(this, arguments);
  51774. this._leftTrigger = 0;
  51775. this._rightTrigger = 0;
  51776. this._buttonA = 0;
  51777. this._buttonB = 0;
  51778. this._buttonX = 0;
  51779. this._buttonY = 0;
  51780. this._buttonBack = 0;
  51781. this._buttonStart = 0;
  51782. this._buttonLB = 0;
  51783. this._buttonRB = 0;
  51784. this._buttonLeftStick = 0;
  51785. this._buttonRightStick = 0;
  51786. this._dPadUp = 0;
  51787. this._dPadDown = 0;
  51788. this._dPadLeft = 0;
  51789. this._dPadRight = 0;
  51790. }
  51791. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51792. this._onlefttriggerchanged = callback;
  51793. };
  51794. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51795. this._onrighttriggerchanged = callback;
  51796. };
  51797. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51798. get: function () {
  51799. return this._leftTrigger;
  51800. },
  51801. set: function (newValue) {
  51802. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51803. this._onlefttriggerchanged(newValue);
  51804. }
  51805. this._leftTrigger = newValue;
  51806. },
  51807. enumerable: true,
  51808. configurable: true
  51809. });
  51810. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51811. get: function () {
  51812. return this._rightTrigger;
  51813. },
  51814. set: function (newValue) {
  51815. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51816. this._onrighttriggerchanged(newValue);
  51817. }
  51818. this._rightTrigger = newValue;
  51819. },
  51820. enumerable: true,
  51821. configurable: true
  51822. });
  51823. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51824. this._onbuttondown = callback;
  51825. };
  51826. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51827. this._onbuttonup = callback;
  51828. };
  51829. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51830. this._ondpaddown = callback;
  51831. };
  51832. Xbox360Pad.prototype.ondpadup = function (callback) {
  51833. this._ondpadup = callback;
  51834. };
  51835. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51836. if (newValue !== currentValue) {
  51837. if (this._onbuttondown && newValue === 1) {
  51838. this._onbuttondown(buttonType);
  51839. }
  51840. if (this._onbuttonup && newValue === 0) {
  51841. this._onbuttonup(buttonType);
  51842. }
  51843. }
  51844. return newValue;
  51845. };
  51846. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51847. if (newValue !== currentValue) {
  51848. if (this._ondpaddown && newValue === 1) {
  51849. this._ondpaddown(buttonType);
  51850. }
  51851. if (this._ondpadup && newValue === 0) {
  51852. this._ondpadup(buttonType);
  51853. }
  51854. }
  51855. return newValue;
  51856. };
  51857. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51858. get: function () {
  51859. return this._buttonA;
  51860. },
  51861. set: function (value) {
  51862. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51868. get: function () {
  51869. return this._buttonB;
  51870. },
  51871. set: function (value) {
  51872. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51873. },
  51874. enumerable: true,
  51875. configurable: true
  51876. });
  51877. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51878. get: function () {
  51879. return this._buttonX;
  51880. },
  51881. set: function (value) {
  51882. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51883. },
  51884. enumerable: true,
  51885. configurable: true
  51886. });
  51887. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51888. get: function () {
  51889. return this._buttonY;
  51890. },
  51891. set: function (value) {
  51892. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51893. },
  51894. enumerable: true,
  51895. configurable: true
  51896. });
  51897. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51898. get: function () {
  51899. return this._buttonStart;
  51900. },
  51901. set: function (value) {
  51902. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51903. },
  51904. enumerable: true,
  51905. configurable: true
  51906. });
  51907. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51908. get: function () {
  51909. return this._buttonBack;
  51910. },
  51911. set: function (value) {
  51912. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51913. },
  51914. enumerable: true,
  51915. configurable: true
  51916. });
  51917. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51918. get: function () {
  51919. return this._buttonLB;
  51920. },
  51921. set: function (value) {
  51922. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51923. },
  51924. enumerable: true,
  51925. configurable: true
  51926. });
  51927. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51928. get: function () {
  51929. return this._buttonRB;
  51930. },
  51931. set: function (value) {
  51932. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51933. },
  51934. enumerable: true,
  51935. configurable: true
  51936. });
  51937. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51938. get: function () {
  51939. return this._buttonLeftStick;
  51940. },
  51941. set: function (value) {
  51942. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51943. },
  51944. enumerable: true,
  51945. configurable: true
  51946. });
  51947. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51948. get: function () {
  51949. return this._buttonRightStick;
  51950. },
  51951. set: function (value) {
  51952. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51953. },
  51954. enumerable: true,
  51955. configurable: true
  51956. });
  51957. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51958. get: function () {
  51959. return this._dPadUp;
  51960. },
  51961. set: function (value) {
  51962. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51968. get: function () {
  51969. return this._dPadDown;
  51970. },
  51971. set: function (value) {
  51972. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51978. get: function () {
  51979. return this._dPadLeft;
  51980. },
  51981. set: function (value) {
  51982. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51988. get: function () {
  51989. return this._dPadRight;
  51990. },
  51991. set: function (value) {
  51992. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Xbox360Pad.prototype.update = function () {
  51998. _super.prototype.update.call(this);
  51999. this.buttonA = this.browserGamepad.buttons[0].value;
  52000. this.buttonB = this.browserGamepad.buttons[1].value;
  52001. this.buttonX = this.browserGamepad.buttons[2].value;
  52002. this.buttonY = this.browserGamepad.buttons[3].value;
  52003. this.buttonLB = this.browserGamepad.buttons[4].value;
  52004. this.buttonRB = this.browserGamepad.buttons[5].value;
  52005. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52006. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52007. this.buttonBack = this.browserGamepad.buttons[8].value;
  52008. this.buttonStart = this.browserGamepad.buttons[9].value;
  52009. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52010. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52011. this.dPadUp = this.browserGamepad.buttons[12].value;
  52012. this.dPadDown = this.browserGamepad.buttons[13].value;
  52013. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52014. this.dPadRight = this.browserGamepad.buttons[15].value;
  52015. };
  52016. return Xbox360Pad;
  52017. })(Gamepad);
  52018. BABYLON.Xbox360Pad = Xbox360Pad;
  52019. })(BABYLON || (BABYLON = {}));
  52020. var BABYLON;
  52021. (function (BABYLON) {
  52022. // We're mainly based on the logic defined into the FreeCamera code
  52023. var GamepadCamera = (function (_super) {
  52024. __extends(GamepadCamera, _super);
  52025. //-- end properties for backward compatibility for inputs
  52026. function GamepadCamera(name, position, scene) {
  52027. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  52028. _super.call(this, name, position, scene);
  52029. }
  52030. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52031. //-- Begin properties for backward compatibility for inputs
  52032. get: function () {
  52033. var gamepad = this.inputs.attached["gamepad"];
  52034. if (gamepad)
  52035. return gamepad.gamepadAngularSensibility;
  52036. },
  52037. set: function (value) {
  52038. var gamepad = this.inputs.attached["gamepad"];
  52039. if (gamepad)
  52040. gamepad.gamepadAngularSensibility = value;
  52041. },
  52042. enumerable: true,
  52043. configurable: true
  52044. });
  52045. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52046. get: function () {
  52047. var gamepad = this.inputs.attached["gamepad"];
  52048. if (gamepad)
  52049. return gamepad.gamepadMoveSensibility;
  52050. },
  52051. set: function (value) {
  52052. var gamepad = this.inputs.attached["gamepad"];
  52053. if (gamepad)
  52054. gamepad.gamepadMoveSensibility = value;
  52055. },
  52056. enumerable: true,
  52057. configurable: true
  52058. });
  52059. GamepadCamera.prototype.getTypeName = function () {
  52060. return "GamepadCamera";
  52061. };
  52062. return GamepadCamera;
  52063. })(BABYLON.UniversalCamera);
  52064. BABYLON.GamepadCamera = GamepadCamera;
  52065. })(BABYLON || (BABYLON = {}));
  52066. var BABYLON;
  52067. (function (BABYLON) {
  52068. var Analyser = (function () {
  52069. function Analyser(scene) {
  52070. this.SMOOTHING = 0.75;
  52071. this.FFT_SIZE = 512;
  52072. this.BARGRAPHAMPLITUDE = 256;
  52073. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  52074. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  52075. this._scene = scene;
  52076. this._audioEngine = BABYLON.Engine.audioEngine;
  52077. if (this._audioEngine.canUseWebAudio) {
  52078. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  52079. this._webAudioAnalyser.minDecibels = -140;
  52080. this._webAudioAnalyser.maxDecibels = 0;
  52081. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52082. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52083. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  52084. }
  52085. }
  52086. Analyser.prototype.getFrequencyBinCount = function () {
  52087. if (this._audioEngine.canUseWebAudio) {
  52088. return this._webAudioAnalyser.frequencyBinCount;
  52089. }
  52090. else {
  52091. return 0;
  52092. }
  52093. };
  52094. Analyser.prototype.getByteFrequencyData = function () {
  52095. if (this._audioEngine.canUseWebAudio) {
  52096. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52097. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52098. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  52099. }
  52100. return this._byteFreqs;
  52101. };
  52102. Analyser.prototype.getByteTimeDomainData = function () {
  52103. if (this._audioEngine.canUseWebAudio) {
  52104. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52105. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52106. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  52107. }
  52108. return this._byteTime;
  52109. };
  52110. Analyser.prototype.getFloatFrequencyData = function () {
  52111. if (this._audioEngine.canUseWebAudio) {
  52112. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52113. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52114. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  52115. }
  52116. return this._floatFreqs;
  52117. };
  52118. Analyser.prototype.drawDebugCanvas = function () {
  52119. var _this = this;
  52120. if (this._audioEngine.canUseWebAudio) {
  52121. if (!this._debugCanvas) {
  52122. this._debugCanvas = document.createElement("canvas");
  52123. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  52124. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  52125. this._debugCanvas.style.position = "absolute";
  52126. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  52127. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  52128. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52129. document.body.appendChild(this._debugCanvas);
  52130. this._registerFunc = function () {
  52131. _this.drawDebugCanvas();
  52132. };
  52133. this._scene.registerBeforeRender(this._registerFunc);
  52134. }
  52135. if (this._registerFunc) {
  52136. var workingArray = this.getByteFrequencyData();
  52137. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52138. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52139. // Draw the frequency domain chart.
  52140. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52141. var value = workingArray[i];
  52142. var percent = value / this.BARGRAPHAMPLITUDE;
  52143. var height = this.DEBUGCANVASSIZE.height * percent;
  52144. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52145. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52146. var hue = i / this.getFrequencyBinCount() * 360;
  52147. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52148. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52149. }
  52150. }
  52151. }
  52152. };
  52153. Analyser.prototype.stopDebugCanvas = function () {
  52154. if (this._debugCanvas) {
  52155. this._scene.unregisterBeforeRender(this._registerFunc);
  52156. this._registerFunc = null;
  52157. document.body.removeChild(this._debugCanvas);
  52158. this._debugCanvas = null;
  52159. this._debugCanvasContext = null;
  52160. }
  52161. };
  52162. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52163. if (this._audioEngine.canUseWebAudio) {
  52164. inputAudioNode.connect(this._webAudioAnalyser);
  52165. this._webAudioAnalyser.connect(outputAudioNode);
  52166. }
  52167. };
  52168. Analyser.prototype.dispose = function () {
  52169. if (this._audioEngine.canUseWebAudio) {
  52170. this._webAudioAnalyser.disconnect();
  52171. }
  52172. };
  52173. return Analyser;
  52174. })();
  52175. BABYLON.Analyser = Analyser;
  52176. })(BABYLON || (BABYLON = {}));
  52177. var BABYLON;
  52178. (function (BABYLON) {
  52179. var DepthRenderer = (function () {
  52180. function DepthRenderer(scene, type) {
  52181. var _this = this;
  52182. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52183. this._viewMatrix = BABYLON.Matrix.Zero();
  52184. this._projectionMatrix = BABYLON.Matrix.Zero();
  52185. this._transformMatrix = BABYLON.Matrix.Zero();
  52186. this._worldViewProjection = BABYLON.Matrix.Zero();
  52187. this._scene = scene;
  52188. var engine = scene.getEngine();
  52189. // Render target
  52190. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52191. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52192. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52193. this._depthMap.refreshRate = 1;
  52194. this._depthMap.renderParticles = false;
  52195. this._depthMap.renderList = null;
  52196. // set default depth value to 1.0 (far away)
  52197. this._depthMap.onClearObservable.add(function (engine) {
  52198. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  52199. });
  52200. // Custom render function
  52201. var renderSubMesh = function (subMesh) {
  52202. var mesh = subMesh.getRenderingMesh();
  52203. var scene = _this._scene;
  52204. var engine = scene.getEngine();
  52205. // Culling
  52206. engine.setState(subMesh.getMaterial().backFaceCulling);
  52207. // Managing instances
  52208. var batch = mesh._getInstancesRenderList(subMesh._id);
  52209. if (batch.mustReturn) {
  52210. return;
  52211. }
  52212. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52213. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52214. engine.enableEffect(_this._effect);
  52215. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52216. var material = subMesh.getMaterial();
  52217. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52218. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  52219. // Alpha test
  52220. if (material && material.needAlphaTesting()) {
  52221. var alphaTexture = material.getAlphaTestTexture();
  52222. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52223. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52224. }
  52225. // Bones
  52226. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52227. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52228. }
  52229. // Draw
  52230. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52231. }
  52232. };
  52233. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52234. var index;
  52235. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52236. renderSubMesh(opaqueSubMeshes.data[index]);
  52237. }
  52238. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52239. renderSubMesh(alphaTestSubMeshes.data[index]);
  52240. }
  52241. };
  52242. }
  52243. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52244. var material = subMesh.getMaterial();
  52245. if (material.disableDepthWrite) {
  52246. return false;
  52247. }
  52248. var defines = [];
  52249. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52250. var mesh = subMesh.getMesh();
  52251. var scene = mesh.getScene();
  52252. // Alpha test
  52253. if (material && material.needAlphaTesting()) {
  52254. defines.push("#define ALPHATEST");
  52255. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52256. attribs.push(BABYLON.VertexBuffer.UVKind);
  52257. defines.push("#define UV1");
  52258. }
  52259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52260. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52261. defines.push("#define UV2");
  52262. }
  52263. }
  52264. // Bones
  52265. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52268. if (mesh.numBoneInfluencers > 4) {
  52269. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52270. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52271. }
  52272. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52273. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52274. }
  52275. else {
  52276. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52277. }
  52278. // Instances
  52279. if (useInstances) {
  52280. defines.push("#define INSTANCES");
  52281. attribs.push("world0");
  52282. attribs.push("world1");
  52283. attribs.push("world2");
  52284. attribs.push("world3");
  52285. }
  52286. // Get correct effect
  52287. var join = defines.join("\n");
  52288. if (this._cachedDefines !== join) {
  52289. this._cachedDefines = join;
  52290. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52291. }
  52292. return this._effect.isReady();
  52293. };
  52294. DepthRenderer.prototype.getDepthMap = function () {
  52295. return this._depthMap;
  52296. };
  52297. // Methods
  52298. DepthRenderer.prototype.dispose = function () {
  52299. this._depthMap.dispose();
  52300. };
  52301. return DepthRenderer;
  52302. })();
  52303. BABYLON.DepthRenderer = DepthRenderer;
  52304. })(BABYLON || (BABYLON = {}));
  52305. var BABYLON;
  52306. (function (BABYLON) {
  52307. var SSAORenderingPipeline = (function (_super) {
  52308. __extends(SSAORenderingPipeline, _super);
  52309. /**
  52310. * @constructor
  52311. * @param {string} name - The rendering pipeline name
  52312. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52313. * @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 }
  52314. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52315. */
  52316. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52317. var _this = this;
  52318. _super.call(this, scene.getEngine(), name);
  52319. // Members
  52320. /**
  52321. * The PassPostProcess id in the pipeline that contains the original scene color
  52322. * @type {string}
  52323. */
  52324. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52325. /**
  52326. * The SSAO PostProcess id in the pipeline
  52327. * @type {string}
  52328. */
  52329. this.SSAORenderEffect = "SSAORenderEffect";
  52330. /**
  52331. * The horizontal blur PostProcess id in the pipeline
  52332. * @type {string}
  52333. */
  52334. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52335. /**
  52336. * The vertical blur PostProcess id in the pipeline
  52337. * @type {string}
  52338. */
  52339. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52340. /**
  52341. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52342. * @type {string}
  52343. */
  52344. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52345. /**
  52346. * The output strength of the SSAO post-process. Default value is 1.0.
  52347. * @type {number}
  52348. */
  52349. this.totalStrength = 1.0;
  52350. /**
  52351. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52352. * @type {number}
  52353. */
  52354. this.radius = 0.0001;
  52355. /**
  52356. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52357. * Must not be equal to fallOff and superior to fallOff.
  52358. * Default value is 0.975
  52359. * @type {number}
  52360. */
  52361. this.area = 0.0075;
  52362. /**
  52363. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52364. * Must not be equal to area and inferior to area.
  52365. * Default value is 0.0
  52366. * @type {number}
  52367. */
  52368. this.fallOff = 0.000001;
  52369. /**
  52370. * The base color of the SSAO post-process
  52371. * The final result is "base + ssao" between [0, 1]
  52372. * @type {number}
  52373. */
  52374. this.base = 0.5;
  52375. this._firstUpdate = true;
  52376. this._scene = scene;
  52377. // Set up assets
  52378. this._createRandomTexture();
  52379. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52380. var ssaoRatio = ratio.ssaoRatio || ratio;
  52381. var combineRatio = ratio.combineRatio || ratio;
  52382. this._ratio = {
  52383. ssaoRatio: ssaoRatio,
  52384. combineRatio: combineRatio
  52385. };
  52386. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52387. this._createSSAOPostProcess(ssaoRatio);
  52388. this._createBlurPostProcess(ssaoRatio);
  52389. this._createSSAOCombinePostProcess(combineRatio);
  52390. // Set up pipeline
  52391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52392. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52396. // Finish
  52397. scene.postProcessRenderPipelineManager.addPipeline(this);
  52398. if (cameras)
  52399. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52400. }
  52401. // Public Methods
  52402. /**
  52403. * Returns the horizontal blur PostProcess
  52404. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  52405. */
  52406. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  52407. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  52408. return null;
  52409. };
  52410. /**
  52411. * Returns the vertical blur PostProcess
  52412. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  52413. */
  52414. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  52415. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  52416. return null;
  52417. };
  52418. /**
  52419. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52420. */
  52421. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52422. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52423. for (var i = 0; i < this._scene.cameras.length; i++) {
  52424. var camera = this._scene.cameras[i];
  52425. this._originalColorPostProcess.dispose(camera);
  52426. this._ssaoPostProcess.dispose(camera);
  52427. this._blurHPostProcess.dispose(camera);
  52428. this._blurVPostProcess.dispose(camera);
  52429. this._ssaoCombinePostProcess.dispose(camera);
  52430. }
  52431. this._randomTexture.dispose();
  52432. if (disableDepthRender)
  52433. this._scene.disableDepthRenderer();
  52434. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52435. };
  52436. // Private Methods
  52437. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52438. var _this = this;
  52439. /*
  52440. var samplerOffsets = [
  52441. -8.0, -6.0, -4.0, -2.0,
  52442. 0.0,
  52443. 2.0, 4.0, 6.0, 8.0
  52444. ];
  52445. */
  52446. var samples = 16;
  52447. var samplerOffsets = [];
  52448. for (var i = -8; i < 8; i++) {
  52449. samplerOffsets.push(i * 2);
  52450. }
  52451. 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");
  52452. this._blurHPostProcess.onApply = function (effect) {
  52453. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52454. effect.setTexture("depthSampler", _this._depthTexture);
  52455. if (_this._firstUpdate) {
  52456. effect.setArray("samplerOffsets", samplerOffsets);
  52457. }
  52458. };
  52459. 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");
  52460. this._blurVPostProcess.onApply = function (effect) {
  52461. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52462. effect.setTexture("depthSampler", _this._depthTexture);
  52463. if (_this._firstUpdate) {
  52464. effect.setArray("samplerOffsets", samplerOffsets);
  52465. _this._firstUpdate = false;
  52466. }
  52467. };
  52468. };
  52469. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52470. var _this = this;
  52471. var numSamples = 16;
  52472. var sampleSphere = [
  52473. 0.5381, 0.1856, -0.4319,
  52474. 0.1379, 0.2486, 0.4430,
  52475. 0.3371, 0.5679, -0.0057,
  52476. -0.6999, -0.0451, -0.0019,
  52477. 0.0689, -0.1598, -0.8547,
  52478. 0.0560, 0.0069, -0.1843,
  52479. -0.0146, 0.1402, 0.0762,
  52480. 0.0100, -0.1924, -0.0344,
  52481. -0.3577, -0.5301, -0.4358,
  52482. -0.3169, 0.1063, 0.0158,
  52483. 0.0103, -0.5869, 0.0046,
  52484. -0.0897, -0.4940, 0.3287,
  52485. 0.7119, -0.0154, -0.0918,
  52486. -0.0533, 0.0596, -0.5411,
  52487. 0.0352, -0.0631, 0.5460,
  52488. -0.4776, 0.2847, -0.0271
  52489. ];
  52490. var samplesFactor = 1.0 / numSamples;
  52491. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52492. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52493. "area", "fallOff", "base", "range", "viewport"
  52494. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52495. var viewport = new BABYLON.Vector2(0, 0);
  52496. this._ssaoPostProcess.onApply = function (effect) {
  52497. if (_this._firstUpdate) {
  52498. effect.setArray3("sampleSphere", sampleSphere);
  52499. effect.setFloat("samplesFactor", samplesFactor);
  52500. effect.setFloat("randTextureTiles", 4.0);
  52501. }
  52502. effect.setFloat("totalStrength", _this.totalStrength);
  52503. effect.setFloat("radius", _this.radius);
  52504. effect.setFloat("area", _this.area);
  52505. effect.setFloat("fallOff", _this.fallOff);
  52506. effect.setFloat("base", _this.base);
  52507. effect.setTexture("textureSampler", _this._depthTexture);
  52508. effect.setTexture("randomSampler", _this._randomTexture);
  52509. };
  52510. };
  52511. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52512. var _this = this;
  52513. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52514. this._ssaoCombinePostProcess.onApply = function (effect) {
  52515. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52516. };
  52517. };
  52518. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52519. var size = 512;
  52520. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52521. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52522. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52523. var context = this._randomTexture.getContext();
  52524. var rand = function (min, max) {
  52525. return Math.random() * (max - min) + min;
  52526. };
  52527. var randVector = BABYLON.Vector3.Zero();
  52528. for (var x = 0; x < size; x++) {
  52529. for (var y = 0; y < size; y++) {
  52530. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52531. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52532. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52533. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52534. context.fillRect(x, y, 1, 1);
  52535. }
  52536. }
  52537. this._randomTexture.update(false);
  52538. };
  52539. __decorate([
  52540. BABYLON.serialize()
  52541. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52542. __decorate([
  52543. BABYLON.serialize()
  52544. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52545. __decorate([
  52546. BABYLON.serialize()
  52547. ], SSAORenderingPipeline.prototype, "area", void 0);
  52548. __decorate([
  52549. BABYLON.serialize()
  52550. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52551. __decorate([
  52552. BABYLON.serialize()
  52553. ], SSAORenderingPipeline.prototype, "base", void 0);
  52554. __decorate([
  52555. BABYLON.serialize()
  52556. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52557. return SSAORenderingPipeline;
  52558. })(BABYLON.PostProcessRenderPipeline);
  52559. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52560. })(BABYLON || (BABYLON = {}));
  52561. var BABYLON;
  52562. (function (BABYLON) {
  52563. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52564. var VolumetricLightScatteringPostProcess = (function (_super) {
  52565. __extends(VolumetricLightScatteringPostProcess, _super);
  52566. /**
  52567. * @constructor
  52568. * @param {string} name - The post-process name
  52569. * @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)
  52570. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52571. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52572. * @param {number} samples - The post-process quality, default 100
  52573. * @param {number} samplingMode - The post-process filtering mode
  52574. * @param {BABYLON.Engine} engine - The babylon engine
  52575. * @param {boolean} reusable - If the post-process is reusable
  52576. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52577. */
  52578. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52579. var _this = this;
  52580. if (samples === void 0) { samples = 100; }
  52581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52582. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  52583. this._screenCoordinates = BABYLON.Vector2.Zero();
  52584. /**
  52585. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52586. * @type {Vector3}
  52587. */
  52588. this.customMeshPosition = BABYLON.Vector3.Zero();
  52589. /**
  52590. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52591. * @type {boolean}
  52592. */
  52593. this.useCustomMeshPosition = false;
  52594. /**
  52595. * If the post-process should inverse the light scattering direction
  52596. * @type {boolean}
  52597. */
  52598. this.invert = true;
  52599. /**
  52600. * Array containing the excluded meshes not rendered in the internal pass
  52601. */
  52602. this.excludedMeshes = new Array();
  52603. /**
  52604. * Controls the overall intensity of the post-process
  52605. * @type {number}
  52606. */
  52607. this.exposure = 0.3;
  52608. /**
  52609. * Dissipates each sample's contribution in range [0, 1]
  52610. * @type {number}
  52611. */
  52612. this.decay = 0.96815;
  52613. /**
  52614. * Controls the overall intensity of each sample
  52615. * @type {number}
  52616. */
  52617. this.weight = 0.58767;
  52618. /**
  52619. * Controls the density of each sample
  52620. * @type {number}
  52621. */
  52622. this.density = 0.926;
  52623. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52624. var engine = scene.getEngine();
  52625. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52626. // Configure mesh
  52627. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52628. // Configure
  52629. this._createPass(scene, ratio.passRatio || ratio);
  52630. this.onActivate = function (camera) {
  52631. if (!_this.isSupported) {
  52632. _this.dispose(camera);
  52633. }
  52634. _this.onActivate = null;
  52635. };
  52636. this.onApplyObservable.add(function (effect) {
  52637. _this._updateMeshScreenCoordinates(scene);
  52638. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52639. effect.setFloat("exposure", _this.exposure);
  52640. effect.setFloat("decay", _this.decay);
  52641. effect.setFloat("weight", _this.weight);
  52642. effect.setFloat("density", _this.density);
  52643. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52644. });
  52645. }
  52646. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52647. get: function () {
  52648. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52649. return false;
  52650. },
  52651. set: function (useDiffuseColor) {
  52652. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52658. var mesh = subMesh.getMesh();
  52659. // Render this.mesh as default
  52660. if (mesh === this.mesh) {
  52661. return mesh.material.isReady(mesh);
  52662. }
  52663. var defines = [];
  52664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52665. var material = subMesh.getMaterial();
  52666. var needUV = false;
  52667. // Alpha test
  52668. if (material) {
  52669. if (material.needAlphaTesting()) {
  52670. defines.push("#define ALPHATEST");
  52671. }
  52672. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52673. attribs.push(BABYLON.VertexBuffer.UVKind);
  52674. defines.push("#define UV1");
  52675. }
  52676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52677. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52678. defines.push("#define UV2");
  52679. }
  52680. }
  52681. // Bones
  52682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52685. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52686. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52687. }
  52688. else {
  52689. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52690. }
  52691. // Instances
  52692. if (useInstances) {
  52693. defines.push("#define INSTANCES");
  52694. attribs.push("world0");
  52695. attribs.push("world1");
  52696. attribs.push("world2");
  52697. attribs.push("world3");
  52698. }
  52699. // Get correct effect
  52700. var join = defines.join("\n");
  52701. if (this._cachedDefines !== join) {
  52702. this._cachedDefines = join;
  52703. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52704. }
  52705. return this._volumetricLightScatteringPass.isReady();
  52706. };
  52707. /**
  52708. * Sets the new light position for light scattering effect
  52709. * @param {BABYLON.Vector3} The new custom light position
  52710. */
  52711. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52712. this.customMeshPosition = position;
  52713. };
  52714. /**
  52715. * Returns the light position for light scattering effect
  52716. * @return {BABYLON.Vector3} The custom light position
  52717. */
  52718. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52719. return this.customMeshPosition;
  52720. };
  52721. /**
  52722. * Disposes the internal assets and detaches the post-process from the camera
  52723. */
  52724. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52725. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52726. if (rttIndex !== -1) {
  52727. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52728. }
  52729. this._volumetricLightScatteringRTT.dispose();
  52730. _super.prototype.dispose.call(this, camera);
  52731. };
  52732. /**
  52733. * Returns the render target texture used by the post-process
  52734. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52735. */
  52736. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52737. return this._volumetricLightScatteringRTT;
  52738. };
  52739. // Private methods
  52740. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52741. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52742. return true;
  52743. }
  52744. return false;
  52745. };
  52746. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52747. var _this = this;
  52748. var engine = scene.getEngine();
  52749. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52750. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52751. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52752. this._volumetricLightScatteringRTT.renderList = null;
  52753. this._volumetricLightScatteringRTT.renderParticles = false;
  52754. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52755. // Custom render function for submeshes
  52756. var renderSubMesh = function (subMesh) {
  52757. var mesh = subMesh.getRenderingMesh();
  52758. if (_this._meshExcluded(mesh)) {
  52759. return;
  52760. }
  52761. var scene = mesh.getScene();
  52762. var engine = scene.getEngine();
  52763. // Culling
  52764. engine.setState(subMesh.getMaterial().backFaceCulling);
  52765. // Managing instances
  52766. var batch = mesh._getInstancesRenderList(subMesh._id);
  52767. if (batch.mustReturn) {
  52768. return;
  52769. }
  52770. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52771. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52772. var effect = _this._volumetricLightScatteringPass;
  52773. if (mesh === _this.mesh) {
  52774. effect = subMesh.getMaterial().getEffect();
  52775. }
  52776. engine.enableEffect(effect);
  52777. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52778. if (mesh === _this.mesh) {
  52779. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52780. }
  52781. else {
  52782. var material = subMesh.getMaterial();
  52783. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52784. // Alpha test
  52785. if (material && material.needAlphaTesting()) {
  52786. var alphaTexture = material.getAlphaTestTexture();
  52787. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52788. if (alphaTexture) {
  52789. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52790. }
  52791. }
  52792. // Bones
  52793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52794. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52795. }
  52796. }
  52797. // Draw
  52798. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52799. }
  52800. };
  52801. // Render target texture callbacks
  52802. var savedSceneClearColor;
  52803. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52804. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52805. savedSceneClearColor = scene.clearColor;
  52806. scene.clearColor = sceneClearColor;
  52807. });
  52808. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52809. scene.clearColor = savedSceneClearColor;
  52810. });
  52811. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52812. var engine = scene.getEngine();
  52813. var index;
  52814. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52815. renderSubMesh(opaqueSubMeshes.data[index]);
  52816. }
  52817. engine.setAlphaTesting(true);
  52818. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52819. renderSubMesh(alphaTestSubMeshes.data[index]);
  52820. }
  52821. engine.setAlphaTesting(false);
  52822. if (transparentSubMeshes.length) {
  52823. // Sort sub meshes
  52824. for (index = 0; index < transparentSubMeshes.length; index++) {
  52825. var submesh = transparentSubMeshes.data[index];
  52826. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52827. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52828. }
  52829. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52830. sortedArray.sort(function (a, b) {
  52831. // Alpha index first
  52832. if (a._alphaIndex > b._alphaIndex) {
  52833. return 1;
  52834. }
  52835. if (a._alphaIndex < b._alphaIndex) {
  52836. return -1;
  52837. }
  52838. // Then distance to camera
  52839. if (a._distanceToCamera < b._distanceToCamera) {
  52840. return 1;
  52841. }
  52842. if (a._distanceToCamera > b._distanceToCamera) {
  52843. return -1;
  52844. }
  52845. return 0;
  52846. });
  52847. // Render sub meshes
  52848. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52849. for (index = 0; index < sortedArray.length; index++) {
  52850. renderSubMesh(sortedArray[index]);
  52851. }
  52852. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52853. }
  52854. };
  52855. };
  52856. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52857. var transform = scene.getTransformMatrix();
  52858. var meshPosition;
  52859. if (this.useCustomMeshPosition) {
  52860. meshPosition = this.customMeshPosition;
  52861. }
  52862. else if (this.attachedNode) {
  52863. meshPosition = this.attachedNode.position;
  52864. }
  52865. else {
  52866. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52867. }
  52868. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52869. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52870. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52871. if (this.invert)
  52872. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52873. };
  52874. // Static methods
  52875. /**
  52876. * Creates a default mesh for the Volumeric Light Scattering post-process
  52877. * @param {string} The mesh name
  52878. * @param {BABYLON.Scene} The scene where to create the mesh
  52879. * @return {BABYLON.Mesh} the default mesh
  52880. */
  52881. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52882. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52883. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52884. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52885. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52886. mesh.material = material;
  52887. return mesh;
  52888. };
  52889. __decorate([
  52890. BABYLON.serializeAsVector3()
  52891. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52892. __decorate([
  52893. BABYLON.serialize()
  52894. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52895. __decorate([
  52896. BABYLON.serialize()
  52897. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52898. __decorate([
  52899. BABYLON.serializeAsMeshReference()
  52900. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52901. __decorate([
  52902. BABYLON.serialize()
  52903. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52904. __decorate([
  52905. BABYLON.serialize()
  52906. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52907. __decorate([
  52908. BABYLON.serialize()
  52909. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52910. __decorate([
  52911. BABYLON.serialize()
  52912. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52913. __decorate([
  52914. BABYLON.serialize()
  52915. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52916. return VolumetricLightScatteringPostProcess;
  52917. })(BABYLON.PostProcess);
  52918. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52919. })(BABYLON || (BABYLON = {}));
  52920. // BABYLON.JS Chromatic Aberration GLSL Shader
  52921. // Author: Olivier Guyot
  52922. // Separates very slightly R, G and B colors on the edges of the screen
  52923. // Inspired by Francois Tarlier & Martins Upitis
  52924. var BABYLON;
  52925. (function (BABYLON) {
  52926. var LensRenderingPipeline = (function (_super) {
  52927. __extends(LensRenderingPipeline, _super);
  52928. /**
  52929. * @constructor
  52930. *
  52931. * Effect parameters are as follow:
  52932. * {
  52933. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52934. * edge_blur: number; // from 0 to x (1 for realism)
  52935. * distortion: number; // from 0 to x (1 for realism)
  52936. * grain_amount: number; // from 0 to 1
  52937. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52938. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52939. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52940. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52941. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52942. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52943. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52944. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52945. * }
  52946. * Note: if an effect parameter is unset, effect is disabled
  52947. *
  52948. * @param {string} name - The rendering pipeline name
  52949. * @param {object} parameters - An object containing all parameters (see above)
  52950. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52951. * @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)
  52952. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52953. */
  52954. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52955. var _this = this;
  52956. if (ratio === void 0) { ratio = 1.0; }
  52957. _super.call(this, scene.getEngine(), name);
  52958. // Lens effects can be of the following:
  52959. // - chromatic aberration (slight shift of RGB colors)
  52960. // - blur on the edge of the lens
  52961. // - lens distortion
  52962. // - depth-of-field blur & highlights enhancing
  52963. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52964. // - grain effect (noise or custom texture)
  52965. // Two additional texture samplers are needed:
  52966. // - depth map (for depth-of-field)
  52967. // - grain texture
  52968. /**
  52969. * The chromatic aberration PostProcess id in the pipeline
  52970. * @type {string}
  52971. */
  52972. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52973. /**
  52974. * The highlights enhancing PostProcess id in the pipeline
  52975. * @type {string}
  52976. */
  52977. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52978. /**
  52979. * The depth-of-field PostProcess id in the pipeline
  52980. * @type {string}
  52981. */
  52982. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52983. this._scene = scene;
  52984. // Fetch texture samplers
  52985. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52986. if (parameters.grain_texture) {
  52987. this._grainTexture = parameters.grain_texture;
  52988. }
  52989. else {
  52990. this._createGrainTexture();
  52991. }
  52992. // save parameters
  52993. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52994. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52995. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52996. this._distortion = parameters.distortion ? parameters.distortion : 0;
  52997. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52998. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52999. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53000. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53001. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53002. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53003. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53004. // Create effects
  53005. this._createChromaticAberrationPostProcess(ratio);
  53006. this._createHighlightsPostProcess(ratio);
  53007. this._createDepthOfFieldPostProcess(ratio / 4);
  53008. // Set up pipeline
  53009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53012. if (this._highlightsGain === -1) {
  53013. this._disableEffect(this.HighlightsEnhancingEffect, null);
  53014. }
  53015. // Finish
  53016. scene.postProcessRenderPipelineManager.addPipeline(this);
  53017. if (cameras) {
  53018. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53019. }
  53020. }
  53021. // public methods (self explanatory)
  53022. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53023. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53024. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53025. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53026. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53027. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53028. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53029. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53030. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53031. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53032. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53033. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53034. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53035. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53036. };
  53037. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53038. this._highlightsPostProcess.updateEffect();
  53039. };
  53040. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53041. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53042. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53043. this._highlightsGain = amount;
  53044. };
  53045. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53046. if (this._highlightsGain === -1) {
  53047. this._highlightsGain = 1.0;
  53048. }
  53049. this._highlightsThreshold = amount;
  53050. };
  53051. LensRenderingPipeline.prototype.disableHighlights = function () {
  53052. this._highlightsGain = -1;
  53053. };
  53054. /**
  53055. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53056. */
  53057. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53058. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53059. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53060. this._chromaticAberrationPostProcess = undefined;
  53061. this._highlightsPostProcess = undefined;
  53062. this._depthOfFieldPostProcess = undefined;
  53063. this._grainTexture.dispose();
  53064. if (disableDepthRender)
  53065. this._scene.disableDepthRenderer();
  53066. };
  53067. // colors shifting and distortion
  53068. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53069. var _this = this;
  53070. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53071. [], // samplers
  53072. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53073. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53074. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53077. };
  53078. };
  53079. // highlights enhancing
  53080. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53081. var _this = this;
  53082. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53083. [], // samplers
  53084. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53085. this._highlightsPostProcess.onApply = function (effect) {
  53086. effect.setFloat('gain', _this._highlightsGain);
  53087. effect.setFloat('threshold', _this._highlightsThreshold);
  53088. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53089. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53090. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53091. };
  53092. };
  53093. // colors shifting and distortion
  53094. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53095. var _this = this;
  53096. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53097. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53098. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53099. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53100. this._depthOfFieldPostProcess.onApply = function (effect) {
  53101. effect.setTexture("depthSampler", _this._depthTexture);
  53102. effect.setTexture("grainSampler", _this._grainTexture);
  53103. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53104. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53105. effect.setFloat('grain_amount', _this._grainAmount);
  53106. effect.setBool('blur_noise', _this._blurNoise);
  53107. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53108. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53109. effect.setFloat('distortion', _this._distortion);
  53110. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53111. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53112. effect.setFloat('aperture', _this._dofAperture);
  53113. effect.setFloat('darken', _this._dofDarken);
  53114. effect.setFloat('edge_blur', _this._edgeBlur);
  53115. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53116. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53117. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53118. };
  53119. };
  53120. // creates a black and white random noise texture, 512x512
  53121. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53122. var size = 512;
  53123. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53124. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53125. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53126. var context = this._grainTexture.getContext();
  53127. var rand = function (min, max) {
  53128. return Math.random() * (max - min) + min;
  53129. };
  53130. var value;
  53131. for (var x = 0; x < size; x++) {
  53132. for (var y = 0; y < size; y++) {
  53133. value = Math.floor(rand(0.42, 0.58) * 255);
  53134. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53135. context.fillRect(x, y, 1, 1);
  53136. }
  53137. }
  53138. this._grainTexture.update(false);
  53139. };
  53140. return LensRenderingPipeline;
  53141. })(BABYLON.PostProcessRenderPipeline);
  53142. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53143. })(BABYLON || (BABYLON = {}));
  53144. //
  53145. // This post-process allows the modification of rendered colors by using
  53146. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53147. //
  53148. // The object needs to be provided an url to a texture containing the color
  53149. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53150. // Use an image editing software to tweak the LUT to match your needs.
  53151. //
  53152. // For an example of a color LUT, see here:
  53153. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53154. // For explanations on color grading, see here:
  53155. // http://udn.epicgames.com/Three/ColorGrading.html
  53156. //
  53157. var BABYLON;
  53158. (function (BABYLON) {
  53159. var ColorCorrectionPostProcess = (function (_super) {
  53160. __extends(ColorCorrectionPostProcess, _super);
  53161. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53162. var _this = this;
  53163. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  53164. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53165. this._colorTableTexture.anisotropicFilteringLevel = 1;
  53166. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53167. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53168. this.onApply = function (effect) {
  53169. effect.setTexture("colorTable", _this._colorTableTexture);
  53170. };
  53171. }
  53172. return ColorCorrectionPostProcess;
  53173. })(BABYLON.PostProcess);
  53174. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53175. })(BABYLON || (BABYLON = {}));
  53176. var BABYLON;
  53177. (function (BABYLON) {
  53178. var AnaglyphFreeCamera = (function (_super) {
  53179. __extends(AnaglyphFreeCamera, _super);
  53180. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  53181. _super.call(this, name, position, scene);
  53182. this.interaxialDistance = interaxialDistance;
  53183. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53184. }
  53185. AnaglyphFreeCamera.prototype.getTypeName = function () {
  53186. return "AnaglyphFreeCamera";
  53187. };
  53188. return AnaglyphFreeCamera;
  53189. })(BABYLON.FreeCamera);
  53190. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  53191. var AnaglyphArcRotateCamera = (function (_super) {
  53192. __extends(AnaglyphArcRotateCamera, _super);
  53193. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  53194. _super.call(this, name, alpha, beta, radius, target, scene);
  53195. this.interaxialDistance = interaxialDistance;
  53196. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53197. }
  53198. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  53199. return "AnaglyphArcRotateCamera";
  53200. };
  53201. return AnaglyphArcRotateCamera;
  53202. })(BABYLON.ArcRotateCamera);
  53203. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  53204. var AnaglyphGamepadCamera = (function (_super) {
  53205. __extends(AnaglyphGamepadCamera, _super);
  53206. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  53207. _super.call(this, name, position, scene);
  53208. this.interaxialDistance = interaxialDistance;
  53209. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53210. }
  53211. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  53212. return "AnaglyphGamepadCamera";
  53213. };
  53214. return AnaglyphGamepadCamera;
  53215. })(BABYLON.GamepadCamera);
  53216. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  53217. var AnaglyphUniversalCamera = (function (_super) {
  53218. __extends(AnaglyphUniversalCamera, _super);
  53219. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  53220. _super.call(this, name, position, scene);
  53221. this.interaxialDistance = interaxialDistance;
  53222. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53223. }
  53224. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  53225. return "AnaglyphUniversalCamera";
  53226. };
  53227. return AnaglyphUniversalCamera;
  53228. })(BABYLON.UniversalCamera);
  53229. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  53230. var StereoscopicFreeCamera = (function (_super) {
  53231. __extends(StereoscopicFreeCamera, _super);
  53232. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53233. _super.call(this, name, position, scene);
  53234. this.interaxialDistance = interaxialDistance;
  53235. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53236. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53237. }
  53238. StereoscopicFreeCamera.prototype.getTypeName = function () {
  53239. return "StereoscopicFreeCamera";
  53240. };
  53241. return StereoscopicFreeCamera;
  53242. })(BABYLON.FreeCamera);
  53243. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  53244. var StereoscopicArcRotateCamera = (function (_super) {
  53245. __extends(StereoscopicArcRotateCamera, _super);
  53246. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  53247. _super.call(this, name, alpha, beta, radius, target, scene);
  53248. this.interaxialDistance = interaxialDistance;
  53249. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53250. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53251. }
  53252. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  53253. return "StereoscopicArcRotateCamera";
  53254. };
  53255. return StereoscopicArcRotateCamera;
  53256. })(BABYLON.ArcRotateCamera);
  53257. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  53258. var StereoscopicGamepadCamera = (function (_super) {
  53259. __extends(StereoscopicGamepadCamera, _super);
  53260. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53261. _super.call(this, name, position, scene);
  53262. this.interaxialDistance = interaxialDistance;
  53263. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53264. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53265. }
  53266. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  53267. return "StereoscopicGamepadCamera";
  53268. };
  53269. return StereoscopicGamepadCamera;
  53270. })(BABYLON.GamepadCamera);
  53271. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53272. var StereoscopicUniversalCamera = (function (_super) {
  53273. __extends(StereoscopicUniversalCamera, _super);
  53274. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53275. _super.call(this, name, position, scene);
  53276. this.interaxialDistance = interaxialDistance;
  53277. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53278. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53279. }
  53280. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  53281. return "StereoscopicUniversalCamera";
  53282. };
  53283. return StereoscopicUniversalCamera;
  53284. })(BABYLON.UniversalCamera);
  53285. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53286. })(BABYLON || (BABYLON = {}));
  53287. var BABYLON;
  53288. (function (BABYLON) {
  53289. var HDRRenderingPipeline = (function (_super) {
  53290. __extends(HDRRenderingPipeline, _super);
  53291. /**
  53292. * @constructor
  53293. * @param {string} name - The rendering pipeline name
  53294. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53295. * @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)
  53296. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53297. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53298. */
  53299. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53300. var _this = this;
  53301. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53302. _super.call(this, scene.getEngine(), name);
  53303. /**
  53304. * Public members
  53305. */
  53306. // Gaussian Blur
  53307. /**
  53308. * Gaussian blur coefficient
  53309. * @type {number}
  53310. */
  53311. this.gaussCoeff = 0.3;
  53312. /**
  53313. * Gaussian blur mean
  53314. * @type {number}
  53315. */
  53316. this.gaussMean = 1.0;
  53317. /**
  53318. * Gaussian blur standard deviation
  53319. * @type {number}
  53320. */
  53321. this.gaussStandDev = 0.8;
  53322. /**
  53323. * Gaussian blur multiplier. Multiplies the blur effect
  53324. * @type {number}
  53325. */
  53326. this.gaussMultiplier = 4.0;
  53327. // HDR
  53328. /**
  53329. * Exposure, controls the overall intensity of the pipeline
  53330. * @type {number}
  53331. */
  53332. this.exposure = 1.0;
  53333. /**
  53334. * Minimum luminance that the post-process can output. Luminance is >= 0
  53335. * @type {number}
  53336. */
  53337. this.minimumLuminance = 1.0;
  53338. /**
  53339. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53340. * @type {number}
  53341. */
  53342. this.maximumLuminance = 1e20;
  53343. /**
  53344. * Increase rate for luminance: eye adaptation speed to dark
  53345. * @type {number}
  53346. */
  53347. this.luminanceIncreaserate = 0.5;
  53348. /**
  53349. * Decrease rate for luminance: eye adaptation speed to bright
  53350. * @type {number}
  53351. */
  53352. this.luminanceDecreaseRate = 0.5;
  53353. // Bright pass
  53354. /**
  53355. * Minimum luminance needed to compute HDR
  53356. * @type {number}
  53357. */
  53358. this.brightThreshold = 0.8;
  53359. this._needUpdate = true;
  53360. this._scene = scene;
  53361. // Bright pass
  53362. this._createBrightPassPostProcess(scene, ratio);
  53363. // Down sample X4
  53364. this._createDownSampleX4PostProcess(scene, ratio);
  53365. // Create gaussian blur post-processes
  53366. this._createGaussianBlurPostProcess(scene, ratio);
  53367. // Texture adder
  53368. this._createTextureAdderPostProcess(scene, ratio);
  53369. // Luminance generator
  53370. this._createLuminanceGeneratorPostProcess(scene);
  53371. // HDR
  53372. this._createHDRPostProcess(scene, ratio);
  53373. // Pass postprocess
  53374. if (originalPostProcess === null) {
  53375. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53376. }
  53377. else {
  53378. this._originalPostProcess = originalPostProcess;
  53379. }
  53380. // Configure pipeline
  53381. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53382. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53383. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53387. var addDownSamplerPostProcess = function (id) {
  53388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53389. };
  53390. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53391. addDownSamplerPostProcess(i);
  53392. }
  53393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53394. // Finish
  53395. scene.postProcessRenderPipelineManager.addPipeline(this);
  53396. if (cameras !== null) {
  53397. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53398. }
  53399. this.update();
  53400. }
  53401. /**
  53402. * Tells the pipeline to update its post-processes
  53403. */
  53404. HDRRenderingPipeline.prototype.update = function () {
  53405. this._needUpdate = true;
  53406. };
  53407. /**
  53408. * Returns the current calculated luminance
  53409. */
  53410. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53411. return this._hdrCurrentLuminance;
  53412. };
  53413. /**
  53414. * Returns the currently drawn luminance
  53415. */
  53416. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53417. return this._hdrOutputLuminance;
  53418. };
  53419. /**
  53420. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53421. */
  53422. HDRRenderingPipeline.prototype.dispose = function () {
  53423. this._originalPostProcess = undefined;
  53424. this._brightPassPostProcess = undefined;
  53425. this._downSampleX4PostProcess = undefined;
  53426. this._guassianBlurHPostProcess = undefined;
  53427. this._guassianBlurVPostProcess = undefined;
  53428. this._textureAdderPostProcess = undefined;
  53429. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53430. this._downSamplePostProcesses[i] = undefined;
  53431. }
  53432. this._hdrPostProcess = undefined;
  53433. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53434. };
  53435. /**
  53436. * Creates the HDR post-process and computes the luminance adaptation
  53437. */
  53438. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53439. var _this = this;
  53440. var hdrLastLuminance = 0.0;
  53441. this._hdrOutputLuminance = -1.0;
  53442. this._hdrCurrentLuminance = 1.0;
  53443. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53444. this._hdrPostProcess.onApply = function (effect) {
  53445. if (_this._hdrOutputLuminance < 0.0) {
  53446. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53447. }
  53448. else {
  53449. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53450. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53451. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53452. }
  53453. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53454. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53455. }
  53456. else {
  53457. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53458. }
  53459. }
  53460. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53461. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53462. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53463. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53464. effect.setFloat("exposure", _this.exposure);
  53465. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53466. _this._needUpdate = false;
  53467. };
  53468. };
  53469. /**
  53470. * Texture Adder post-process
  53471. */
  53472. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53473. var _this = this;
  53474. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53475. this._textureAdderPostProcess.onApply = function (effect) {
  53476. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53477. };
  53478. };
  53479. /**
  53480. * Down sample X4 post-process
  53481. */
  53482. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53483. var _this = this;
  53484. var downSampleX4Offsets = new Array(32);
  53485. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53486. this._downSampleX4PostProcess.onApply = function (effect) {
  53487. if (_this._needUpdate) {
  53488. var id = 0;
  53489. for (var i = -2; i < 2; i++) {
  53490. for (var j = -2; j < 2; j++) {
  53491. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53492. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53493. id += 2;
  53494. }
  53495. }
  53496. }
  53497. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53498. };
  53499. };
  53500. /**
  53501. * Bright pass post-process
  53502. */
  53503. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53504. var _this = this;
  53505. var brightOffsets = new Array(8);
  53506. var brightPassCallback = function (effect) {
  53507. if (_this._needUpdate) {
  53508. var sU = (1.0 / _this._brightPassPostProcess.width);
  53509. var sV = (1.0 / _this._brightPassPostProcess.height);
  53510. brightOffsets[0] = -0.5 * sU;
  53511. brightOffsets[1] = 0.5 * sV;
  53512. brightOffsets[2] = 0.5 * sU;
  53513. brightOffsets[3] = 0.5 * sV;
  53514. brightOffsets[4] = -0.5 * sU;
  53515. brightOffsets[5] = -0.5 * sV;
  53516. brightOffsets[6] = 0.5 * sU;
  53517. brightOffsets[7] = -0.5 * sV;
  53518. }
  53519. effect.setArray2("dsOffsets", brightOffsets);
  53520. effect.setFloat("brightThreshold", _this.brightThreshold);
  53521. };
  53522. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53523. this._brightPassPostProcess.onApply = brightPassCallback;
  53524. };
  53525. /**
  53526. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53527. */
  53528. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53529. var _this = this;
  53530. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53531. var luminanceOffsets = new Array(8);
  53532. var downSampleOffsets = new Array(18);
  53533. var halfDestPixelSize;
  53534. this._downSamplePostProcesses = new Array(lumSteps);
  53535. // Utils for luminance
  53536. var luminanceUpdateSourceOffsets = function (width, height) {
  53537. var sU = (1.0 / width);
  53538. var sV = (1.0 / height);
  53539. luminanceOffsets[0] = -0.5 * sU;
  53540. luminanceOffsets[1] = 0.5 * sV;
  53541. luminanceOffsets[2] = 0.5 * sU;
  53542. luminanceOffsets[3] = 0.5 * sV;
  53543. luminanceOffsets[4] = -0.5 * sU;
  53544. luminanceOffsets[5] = -0.5 * sV;
  53545. luminanceOffsets[6] = 0.5 * sU;
  53546. luminanceOffsets[7] = -0.5 * sV;
  53547. };
  53548. var luminanceUpdateDestOffsets = function (width, height) {
  53549. var id = 0;
  53550. for (var x = -1; x < 2; x++) {
  53551. for (var y = -1; y < 2; y++) {
  53552. downSampleOffsets[id] = (x) / width;
  53553. downSampleOffsets[id + 1] = (y) / height;
  53554. id += 2;
  53555. }
  53556. }
  53557. };
  53558. // Luminance callback
  53559. var luminanceCallback = function (effect) {
  53560. if (_this._needUpdate) {
  53561. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53562. }
  53563. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53564. effect.setArray2("lumOffsets", luminanceOffsets);
  53565. };
  53566. // Down sample callbacks
  53567. var downSampleCallback = function (indice) {
  53568. var i = indice;
  53569. return function (effect) {
  53570. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53571. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53572. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53573. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53574. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53575. effect.setArray2("dsOffsets", downSampleOffsets);
  53576. };
  53577. };
  53578. var downSampleAfterRenderCallback = function (effect) {
  53579. // Unpack result
  53580. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53581. 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);
  53582. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53583. };
  53584. // Create luminance post-process
  53585. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53586. 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);
  53587. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53588. // Create down sample post-processes
  53589. for (var i = lumSteps - 2; i >= 0; i--) {
  53590. var length = Math.pow(3, i);
  53591. ratio = { width: length, height: length };
  53592. var defines = "#define DOWN_SAMPLE\n";
  53593. if (i === 0) {
  53594. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53595. }
  53596. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53597. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53598. if (i === 0) {
  53599. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53600. }
  53601. }
  53602. };
  53603. /**
  53604. * Gaussian blur post-processes. Horizontal and Vertical
  53605. */
  53606. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53607. var _this = this;
  53608. var blurOffsetsW = new Array(9);
  53609. var blurOffsetsH = new Array(9);
  53610. var blurWeights = new Array(9);
  53611. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53612. // Utils for gaussian blur
  53613. var calculateBlurOffsets = function (height) {
  53614. var lastOutputDimensions = {
  53615. width: scene.getEngine().getRenderWidth(),
  53616. height: scene.getEngine().getRenderHeight()
  53617. };
  53618. for (var i = 0; i < 9; i++) {
  53619. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53620. if (height) {
  53621. blurOffsetsH[i] = value;
  53622. }
  53623. else {
  53624. blurOffsetsW[i] = value;
  53625. }
  53626. }
  53627. };
  53628. var calculateWeights = function () {
  53629. var x = 0.0;
  53630. for (var i = 0; i < 9; i++) {
  53631. x = (i - 4.0) / 4.0;
  53632. 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));
  53633. }
  53634. };
  53635. // Callback
  53636. var gaussianBlurCallback = function (height) {
  53637. return function (effect) {
  53638. if (_this._needUpdate) {
  53639. calculateWeights();
  53640. calculateBlurOffsets(height);
  53641. }
  53642. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53643. effect.setArray("blurWeights", blurWeights);
  53644. effect.setFloat("multiplier", _this.gaussMultiplier);
  53645. };
  53646. };
  53647. // Create horizontal gaussian blur post-processes
  53648. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53649. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53650. // Create vertical gaussian blur post-process
  53651. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53652. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53653. };
  53654. // Luminance generator
  53655. HDRRenderingPipeline.LUM_STEPS = 6;
  53656. return HDRRenderingPipeline;
  53657. })(BABYLON.PostProcessRenderPipeline);
  53658. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53659. })(BABYLON || (BABYLON = {}));
  53660. var BABYLON;
  53661. (function (BABYLON) {
  53662. var FaceAdjacencies = (function () {
  53663. function FaceAdjacencies() {
  53664. this.edges = new Array();
  53665. this.edgesConnectedCount = 0;
  53666. }
  53667. return FaceAdjacencies;
  53668. })();
  53669. var EdgesRenderer = (function () {
  53670. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53671. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53672. if (epsilon === void 0) { epsilon = 0.95; }
  53673. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53674. this.edgesWidthScalerForOrthographic = 1000.0;
  53675. this.edgesWidthScalerForPerspective = 50.0;
  53676. this._linesPositions = new Array();
  53677. this._linesNormals = new Array();
  53678. this._linesIndices = new Array();
  53679. this._buffers = {};
  53680. this._checkVerticesInsteadOfIndices = false;
  53681. this._source = source;
  53682. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53683. this._epsilon = epsilon;
  53684. this._prepareRessources();
  53685. this._generateEdgesLines();
  53686. }
  53687. EdgesRenderer.prototype._prepareRessources = function () {
  53688. if (this._lineShader) {
  53689. return;
  53690. }
  53691. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53692. attributes: ["position", "normal"],
  53693. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53694. });
  53695. this._lineShader.disableDepthWrite = true;
  53696. this._lineShader.backFaceCulling = false;
  53697. };
  53698. EdgesRenderer.prototype.dispose = function () {
  53699. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53700. if (buffer) {
  53701. buffer.dispose();
  53702. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53703. }
  53704. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53705. if (buffer) {
  53706. buffer.dispose();
  53707. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53708. }
  53709. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53710. this._lineShader.dispose();
  53711. };
  53712. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53713. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53714. return 0;
  53715. }
  53716. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53717. return 1;
  53718. }
  53719. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53720. return 2;
  53721. }
  53722. return -1;
  53723. };
  53724. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53725. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53726. return 0;
  53727. }
  53728. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53729. return 1;
  53730. }
  53731. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53732. return 2;
  53733. }
  53734. return -1;
  53735. };
  53736. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53737. var needToCreateLine;
  53738. if (edge === undefined) {
  53739. needToCreateLine = true;
  53740. }
  53741. else {
  53742. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53743. needToCreateLine = dotProduct < this._epsilon;
  53744. }
  53745. if (needToCreateLine) {
  53746. var offset = this._linesPositions.length / 3;
  53747. var normal = p0.subtract(p1);
  53748. normal.normalize();
  53749. // Positions
  53750. this._linesPositions.push(p0.x);
  53751. this._linesPositions.push(p0.y);
  53752. this._linesPositions.push(p0.z);
  53753. this._linesPositions.push(p0.x);
  53754. this._linesPositions.push(p0.y);
  53755. this._linesPositions.push(p0.z);
  53756. this._linesPositions.push(p1.x);
  53757. this._linesPositions.push(p1.y);
  53758. this._linesPositions.push(p1.z);
  53759. this._linesPositions.push(p1.x);
  53760. this._linesPositions.push(p1.y);
  53761. this._linesPositions.push(p1.z);
  53762. // Normals
  53763. this._linesNormals.push(p1.x);
  53764. this._linesNormals.push(p1.y);
  53765. this._linesNormals.push(p1.z);
  53766. this._linesNormals.push(-1);
  53767. this._linesNormals.push(p1.x);
  53768. this._linesNormals.push(p1.y);
  53769. this._linesNormals.push(p1.z);
  53770. this._linesNormals.push(1);
  53771. this._linesNormals.push(p0.x);
  53772. this._linesNormals.push(p0.y);
  53773. this._linesNormals.push(p0.z);
  53774. this._linesNormals.push(-1);
  53775. this._linesNormals.push(p0.x);
  53776. this._linesNormals.push(p0.y);
  53777. this._linesNormals.push(p0.z);
  53778. this._linesNormals.push(1);
  53779. // Indices
  53780. this._linesIndices.push(offset);
  53781. this._linesIndices.push(offset + 1);
  53782. this._linesIndices.push(offset + 2);
  53783. this._linesIndices.push(offset);
  53784. this._linesIndices.push(offset + 2);
  53785. this._linesIndices.push(offset + 3);
  53786. }
  53787. };
  53788. EdgesRenderer.prototype._generateEdgesLines = function () {
  53789. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53790. var indices = this._source.getIndices();
  53791. // First let's find adjacencies
  53792. var adjacencies = new Array();
  53793. var faceNormals = new Array();
  53794. var index;
  53795. var faceAdjacencies;
  53796. // Prepare faces
  53797. for (index = 0; index < indices.length; index += 3) {
  53798. faceAdjacencies = new FaceAdjacencies();
  53799. var p0Index = indices[index];
  53800. var p1Index = indices[index + 1];
  53801. var p2Index = indices[index + 2];
  53802. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53803. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53804. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53805. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53806. faceNormal.normalize();
  53807. faceNormals.push(faceNormal);
  53808. adjacencies.push(faceAdjacencies);
  53809. }
  53810. // Scan
  53811. for (index = 0; index < adjacencies.length; index++) {
  53812. faceAdjacencies = adjacencies[index];
  53813. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53814. var otherFaceAdjacencies = adjacencies[otherIndex];
  53815. if (faceAdjacencies.edgesConnectedCount === 3) {
  53816. break;
  53817. }
  53818. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53819. continue;
  53820. }
  53821. var otherP0 = indices[otherIndex * 3];
  53822. var otherP1 = indices[otherIndex * 3 + 1];
  53823. var otherP2 = indices[otherIndex * 3 + 2];
  53824. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53825. var otherEdgeIndex;
  53826. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53827. continue;
  53828. }
  53829. switch (edgeIndex) {
  53830. case 0:
  53831. if (this._checkVerticesInsteadOfIndices) {
  53832. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53833. }
  53834. else {
  53835. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53836. }
  53837. break;
  53838. case 1:
  53839. if (this._checkVerticesInsteadOfIndices) {
  53840. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53841. }
  53842. else {
  53843. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53844. }
  53845. break;
  53846. case 2:
  53847. if (this._checkVerticesInsteadOfIndices) {
  53848. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53849. }
  53850. else {
  53851. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53852. }
  53853. break;
  53854. }
  53855. if (otherEdgeIndex === -1) {
  53856. continue;
  53857. }
  53858. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53859. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53860. faceAdjacencies.edgesConnectedCount++;
  53861. otherFaceAdjacencies.edgesConnectedCount++;
  53862. if (faceAdjacencies.edgesConnectedCount === 3) {
  53863. break;
  53864. }
  53865. }
  53866. }
  53867. }
  53868. // Create lines
  53869. for (index = 0; index < adjacencies.length; index++) {
  53870. // 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
  53871. var current = adjacencies[index];
  53872. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53873. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53874. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53875. }
  53876. // Merge into a single mesh
  53877. var engine = this._source.getScene().getEngine();
  53878. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53879. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53880. this._ib = engine.createIndexBuffer(this._linesIndices);
  53881. this._indicesCount = this._linesIndices.length;
  53882. };
  53883. EdgesRenderer.prototype.render = function () {
  53884. if (!this._lineShader.isReady()) {
  53885. return;
  53886. }
  53887. var scene = this._source.getScene();
  53888. var engine = scene.getEngine();
  53889. this._lineShader._preBind();
  53890. // VBOs
  53891. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53892. scene.resetCachedMaterial();
  53893. this._lineShader.setColor4("color", this._source.edgesColor);
  53894. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53895. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53896. }
  53897. else {
  53898. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53899. }
  53900. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53901. this._lineShader.bind(this._source.getWorldMatrix());
  53902. // Draw order
  53903. engine.draw(true, 0, this._indicesCount);
  53904. this._lineShader.unbind();
  53905. engine.setDepthWrite(true);
  53906. };
  53907. return EdgesRenderer;
  53908. })();
  53909. BABYLON.EdgesRenderer = EdgesRenderer;
  53910. })(BABYLON || (BABYLON = {}));
  53911. var BABYLON;
  53912. (function (BABYLON) {
  53913. (function (TonemappingOperator) {
  53914. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53915. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53916. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53917. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53918. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53919. var TonemappingOperator = BABYLON.TonemappingOperator;
  53920. ;
  53921. var TonemapPostProcess = (function (_super) {
  53922. __extends(TonemapPostProcess, _super);
  53923. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53924. var _this = this;
  53925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53926. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53927. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  53928. this._operator = _operator;
  53929. this.exposureAdjustment = exposureAdjustment;
  53930. var defines = "#define ";
  53931. if (this._operator === TonemappingOperator.Hable)
  53932. defines += "HABLE_TONEMAPPING";
  53933. else if (this._operator === TonemappingOperator.Reinhard)
  53934. defines += "REINHARD_TONEMAPPING";
  53935. else if (this._operator === TonemappingOperator.HejiDawson)
  53936. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53937. else if (this._operator === TonemappingOperator.Photographic)
  53938. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53939. //sadly a second call to create the effect.
  53940. this.updateEffect(defines);
  53941. this.onApply = function (effect) {
  53942. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53943. };
  53944. }
  53945. return TonemapPostProcess;
  53946. })(BABYLON.PostProcess);
  53947. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53948. })(BABYLON || (BABYLON = {}));
  53949. var BABYLON;
  53950. (function (BABYLON) {
  53951. var ReflectionProbe = (function () {
  53952. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53953. var _this = this;
  53954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53955. this.name = name;
  53956. this._viewMatrix = BABYLON.Matrix.Identity();
  53957. this._target = BABYLON.Vector3.Zero();
  53958. this._add = BABYLON.Vector3.Zero();
  53959. this.invertYAxis = false;
  53960. this.position = BABYLON.Vector3.Zero();
  53961. this._scene = scene;
  53962. this._scene.reflectionProbes.push(this);
  53963. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53964. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53965. switch (faceIndex) {
  53966. case 0:
  53967. _this._add.copyFromFloats(1, 0, 0);
  53968. break;
  53969. case 1:
  53970. _this._add.copyFromFloats(-1, 0, 0);
  53971. break;
  53972. case 2:
  53973. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53974. break;
  53975. case 3:
  53976. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53977. break;
  53978. case 4:
  53979. _this._add.copyFromFloats(0, 0, 1);
  53980. break;
  53981. case 5:
  53982. _this._add.copyFromFloats(0, 0, -1);
  53983. break;
  53984. }
  53985. if (_this._attachedMesh) {
  53986. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53987. }
  53988. _this.position.addToRef(_this._add, _this._target);
  53989. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53990. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53991. });
  53992. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53993. scene.updateTransformMatrix(true);
  53994. });
  53995. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53996. }
  53997. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53998. get: function () {
  53999. return this._renderTargetTexture.refreshRate;
  54000. },
  54001. set: function (value) {
  54002. this._renderTargetTexture.refreshRate = value;
  54003. },
  54004. enumerable: true,
  54005. configurable: true
  54006. });
  54007. ReflectionProbe.prototype.getScene = function () {
  54008. return this._scene;
  54009. };
  54010. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  54011. get: function () {
  54012. return this._renderTargetTexture;
  54013. },
  54014. enumerable: true,
  54015. configurable: true
  54016. });
  54017. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  54018. get: function () {
  54019. return this._renderTargetTexture.renderList;
  54020. },
  54021. enumerable: true,
  54022. configurable: true
  54023. });
  54024. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  54025. this._attachedMesh = mesh;
  54026. };
  54027. ReflectionProbe.prototype.dispose = function () {
  54028. var index = this._scene.reflectionProbes.indexOf(this);
  54029. if (index !== -1) {
  54030. // Remove from the scene if found
  54031. this._scene.reflectionProbes.splice(index, 1);
  54032. }
  54033. if (this._renderTargetTexture) {
  54034. this._renderTargetTexture.dispose();
  54035. this._renderTargetTexture = null;
  54036. }
  54037. };
  54038. return ReflectionProbe;
  54039. })();
  54040. BABYLON.ReflectionProbe = ReflectionProbe;
  54041. })(BABYLON || (BABYLON = {}));
  54042. var BABYLON;
  54043. (function (BABYLON) {
  54044. var SolidParticle = (function () {
  54045. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  54046. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  54047. this.position = BABYLON.Vector3.Zero(); // position
  54048. this.rotation = BABYLON.Vector3.Zero(); // rotation
  54049. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  54050. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  54051. this.velocity = BABYLON.Vector3.Zero(); // velocity
  54052. this.alive = true; // alive
  54053. this.isVisible = true; // visibility
  54054. this.idx = particleIndex;
  54055. this._pos = positionIndex;
  54056. this._model = model;
  54057. this.shapeId = shapeId;
  54058. this.idxInShape = idxInShape;
  54059. }
  54060. Object.defineProperty(SolidParticle.prototype, "scale", {
  54061. //legacy support, changed scale to scaling
  54062. get: function () {
  54063. return this.scaling;
  54064. },
  54065. set: function (scale) {
  54066. this.scaling = scale;
  54067. },
  54068. enumerable: true,
  54069. configurable: true
  54070. });
  54071. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54072. //legacy support, changed quaternion to rotationQuaternion
  54073. get: function () {
  54074. return this.rotationQuaternion;
  54075. },
  54076. set: function (q) {
  54077. this.rotationQuaternion = q;
  54078. },
  54079. enumerable: true,
  54080. configurable: true
  54081. });
  54082. return SolidParticle;
  54083. })();
  54084. BABYLON.SolidParticle = SolidParticle;
  54085. var ModelShape = (function () {
  54086. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  54087. this.shapeID = id;
  54088. this._shape = shape;
  54089. this._shapeUV = shapeUV;
  54090. this._positionFunction = posFunction;
  54091. this._vertexFunction = vtxFunction;
  54092. }
  54093. return ModelShape;
  54094. })();
  54095. BABYLON.ModelShape = ModelShape;
  54096. })(BABYLON || (BABYLON = {}));
  54097. var BABYLON;
  54098. (function (BABYLON) {
  54099. /**
  54100. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54101. */
  54102. var SolidParticleSystem = (function () {
  54103. /**
  54104. * Creates a SPS (Solid Particle System) object.
  54105. * `name` (String) is the SPS name, this will be the underlying mesh name.
  54106. * `scene` (Scene) is the scene in which the SPS is added.
  54107. * `updatable` (default true) : if the SPS must be updatable or immutable.
  54108. * `isPickable` (default false) : if the solid particles must be pickable.
  54109. */
  54110. function SolidParticleSystem(name, scene, options) {
  54111. // public members
  54112. /**
  54113. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54114. * Example : var p = SPS.particles[i];
  54115. */
  54116. this.particles = new Array();
  54117. /**
  54118. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54119. */
  54120. this.nbParticles = 0;
  54121. /**
  54122. * If the particles must ever face the camera (default false). Useful for planar particles.
  54123. */
  54124. this.billboard = false;
  54125. /**
  54126. * This a counter ofr your own usage. It's not set by any SPS functions.
  54127. */
  54128. this.counter = 0;
  54129. /**
  54130. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54131. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54132. */
  54133. this.vars = {};
  54134. this._positions = new Array();
  54135. this._indices = new Array();
  54136. this._normals = new Array();
  54137. this._colors = new Array();
  54138. this._uvs = new Array();
  54139. this._index = 0; // indices index
  54140. this._updatable = true;
  54141. this._pickable = false;
  54142. this._isVisibilityBoxLocked = false;
  54143. this._alwaysVisible = false;
  54144. this._shapeCounter = 0;
  54145. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  54146. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54147. this._computeParticleColor = true;
  54148. this._computeParticleTexture = true;
  54149. this._computeParticleRotation = true;
  54150. this._computeParticleVertex = false;
  54151. this._computeBoundingBox = false;
  54152. this._cam_axisZ = BABYLON.Vector3.Zero();
  54153. this._cam_axisY = BABYLON.Vector3.Zero();
  54154. this._cam_axisX = BABYLON.Vector3.Zero();
  54155. this._axisX = BABYLON.Axis.X;
  54156. this._axisY = BABYLON.Axis.Y;
  54157. this._axisZ = BABYLON.Axis.Z;
  54158. this._fakeCamPos = BABYLON.Vector3.Zero();
  54159. this._rotMatrix = new BABYLON.Matrix();
  54160. this._invertMatrix = new BABYLON.Matrix();
  54161. this._rotated = BABYLON.Vector3.Zero();
  54162. this._quaternion = new BABYLON.Quaternion();
  54163. this._vertex = BABYLON.Vector3.Zero();
  54164. this._normal = BABYLON.Vector3.Zero();
  54165. this._yaw = 0.0;
  54166. this._pitch = 0.0;
  54167. this._roll = 0.0;
  54168. this._halfroll = 0.0;
  54169. this._halfpitch = 0.0;
  54170. this._halfyaw = 0.0;
  54171. this._sinRoll = 0.0;
  54172. this._cosRoll = 0.0;
  54173. this._sinPitch = 0.0;
  54174. this._cosPitch = 0.0;
  54175. this._sinYaw = 0.0;
  54176. this._cosYaw = 0.0;
  54177. this._w = 0.0;
  54178. this._minimum = BABYLON.Tmp.Vector3[0];
  54179. this._maximum = BABYLON.Tmp.Vector3[1];
  54180. this.name = name;
  54181. this._scene = scene;
  54182. this._camera = scene.activeCamera;
  54183. this._pickable = options ? options.isPickable : false;
  54184. if (options && options.updatable) {
  54185. this._updatable = options.updatable;
  54186. }
  54187. else {
  54188. this._updatable = true;
  54189. }
  54190. if (this._pickable) {
  54191. this.pickedParticles = [];
  54192. }
  54193. }
  54194. /**
  54195. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54196. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54197. */
  54198. SolidParticleSystem.prototype.buildMesh = function () {
  54199. if (this.nbParticles === 0) {
  54200. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54201. this.addShape(triangle, 1);
  54202. triangle.dispose();
  54203. }
  54204. this._positions32 = new Float32Array(this._positions);
  54205. this._uvs32 = new Float32Array(this._uvs);
  54206. this._colors32 = new Float32Array(this._colors);
  54207. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54208. this._normals32 = new Float32Array(this._normals);
  54209. this._fixedNormal32 = new Float32Array(this._normals);
  54210. var vertexData = new BABYLON.VertexData();
  54211. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54212. vertexData.indices = this._indices;
  54213. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54214. if (this._uvs32) {
  54215. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54216. ;
  54217. }
  54218. if (this._colors32) {
  54219. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54220. }
  54221. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54222. vertexData.applyToMesh(mesh, this._updatable);
  54223. this.mesh = mesh;
  54224. this.mesh.isPickable = this._pickable;
  54225. // free memory
  54226. this._positions = null;
  54227. this._normals = null;
  54228. this._uvs = null;
  54229. this._colors = null;
  54230. if (!this._updatable) {
  54231. this.particles.length = 0;
  54232. }
  54233. return mesh;
  54234. };
  54235. /**
  54236. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54237. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54238. * Thus the particles generated from `digest()` have their property `position` set yet.
  54239. * `mesh` ( Mesh ) is the mesh to be digested
  54240. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54241. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54242. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54243. */
  54244. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54245. var size = (options && options.facetNb) || 1;
  54246. var number = (options && options.number);
  54247. var delta = (options && options.delta) || 0;
  54248. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54249. var meshInd = mesh.getIndices();
  54250. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54251. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54252. var f = 0; // facet counter
  54253. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54254. // compute size from number
  54255. if (number) {
  54256. number = (number > totalFacets) ? totalFacets : number;
  54257. size = Math.round(totalFacets / number);
  54258. delta = 0;
  54259. }
  54260. else {
  54261. size = (size > totalFacets) ? totalFacets : size;
  54262. }
  54263. var facetPos = []; // submesh positions
  54264. var facetInd = []; // submesh indices
  54265. var facetUV = []; // submesh UV
  54266. var facetCol = []; // submesh colors
  54267. var barycenter = BABYLON.Tmp.Vector3[0];
  54268. var rand;
  54269. var sizeO = size;
  54270. while (f < totalFacets) {
  54271. size = sizeO + Math.floor((1 + delta) * Math.random());
  54272. if (f > totalFacets - size) {
  54273. size = totalFacets - f;
  54274. }
  54275. // reset temp arrays
  54276. facetPos.length = 0;
  54277. facetInd.length = 0;
  54278. facetUV.length = 0;
  54279. facetCol.length = 0;
  54280. // iterate over "size" facets
  54281. var fi = 0;
  54282. for (var j = f * 3; j < (f + size) * 3; j++) {
  54283. facetInd.push(fi);
  54284. var i = meshInd[j];
  54285. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54286. if (meshUV) {
  54287. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54288. }
  54289. if (meshCol) {
  54290. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54291. }
  54292. fi++;
  54293. }
  54294. // create a model shape for each single particle
  54295. var idx = this.nbParticles;
  54296. var shape = this._posToShape(facetPos);
  54297. var shapeUV = this._uvsToShapeUV(facetUV);
  54298. // compute the barycenter of the shape
  54299. var v;
  54300. for (v = 0; v < shape.length; v++) {
  54301. barycenter.addInPlace(shape[v]);
  54302. }
  54303. barycenter.scaleInPlace(1 / shape.length);
  54304. // shift the shape from its barycenter to the origin
  54305. for (v = 0; v < shape.length; v++) {
  54306. shape[v].subtractInPlace(barycenter);
  54307. }
  54308. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54309. // add the particle in the SPS
  54310. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  54311. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  54312. // initialize the particle position
  54313. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54314. this._index += shape.length;
  54315. idx++;
  54316. this.nbParticles++;
  54317. this._shapeCounter++;
  54318. f += size;
  54319. }
  54320. return this;
  54321. };
  54322. //reset copy
  54323. SolidParticleSystem.prototype._resetCopy = function () {
  54324. this._copy.position.x = 0;
  54325. this._copy.position.y = 0;
  54326. this._copy.position.z = 0;
  54327. this._copy.rotation.x = 0;
  54328. this._copy.rotation.y = 0;
  54329. this._copy.rotation.z = 0;
  54330. this._copy.rotationQuaternion = null;
  54331. this._copy.scaling.x = 1;
  54332. this._copy.scaling.y = 1;
  54333. this._copy.scaling.z = 1;
  54334. this._copy.uvs.x = 0;
  54335. this._copy.uvs.y = 0;
  54336. this._copy.uvs.z = 1;
  54337. this._copy.uvs.w = 1;
  54338. this._copy.color = null;
  54339. };
  54340. // _meshBuilder : inserts the shape model in the global SPS mesh
  54341. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  54342. var i;
  54343. var u = 0;
  54344. var c = 0;
  54345. this._resetCopy();
  54346. if (options && options.positionFunction) {
  54347. options.positionFunction(this._copy, idx, idxInShape);
  54348. }
  54349. if (this._copy.rotationQuaternion) {
  54350. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54351. }
  54352. else {
  54353. this._yaw = this._copy.rotation.y;
  54354. this._pitch = this._copy.rotation.x;
  54355. this._roll = this._copy.rotation.z;
  54356. this._quaternionRotationYPR();
  54357. }
  54358. this._quaternionToRotationMatrix();
  54359. for (i = 0; i < shape.length; i++) {
  54360. this._vertex.x = shape[i].x;
  54361. this._vertex.y = shape[i].y;
  54362. this._vertex.z = shape[i].z;
  54363. if (options && options.vertexFunction) {
  54364. options.vertexFunction(this._copy, this._vertex, i);
  54365. }
  54366. this._vertex.x *= this._copy.scaling.x;
  54367. this._vertex.y *= this._copy.scaling.y;
  54368. this._vertex.z *= this._copy.scaling.z;
  54369. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54370. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54371. if (meshUV) {
  54372. 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);
  54373. u += 2;
  54374. }
  54375. if (this._copy.color) {
  54376. this._color = this._copy.color;
  54377. }
  54378. else if (meshCol && meshCol[c] !== undefined) {
  54379. this._color.r = meshCol[c];
  54380. this._color.g = meshCol[c + 1];
  54381. this._color.b = meshCol[c + 2];
  54382. this._color.a = meshCol[c + 3];
  54383. }
  54384. else {
  54385. this._color.r = 1;
  54386. this._color.g = 1;
  54387. this._color.b = 1;
  54388. this._color.a = 1;
  54389. }
  54390. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54391. c += 4;
  54392. }
  54393. for (i = 0; i < meshInd.length; i++) {
  54394. indices.push(p + meshInd[i]);
  54395. }
  54396. if (this._pickable) {
  54397. var nbfaces = meshInd.length / 3;
  54398. for (i = 0; i < nbfaces; i++) {
  54399. this.pickedParticles.push({ idx: idx, faceId: i });
  54400. }
  54401. }
  54402. };
  54403. // returns a shape array from positions array
  54404. SolidParticleSystem.prototype._posToShape = function (positions) {
  54405. var shape = [];
  54406. for (var i = 0; i < positions.length; i += 3) {
  54407. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54408. }
  54409. return shape;
  54410. };
  54411. // returns a shapeUV array from a Vector4 uvs
  54412. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54413. var shapeUV = [];
  54414. if (uvs) {
  54415. for (var i = 0; i < uvs.length; i++)
  54416. shapeUV.push(uvs[i]);
  54417. }
  54418. return shapeUV;
  54419. };
  54420. // adds a new particle object in the particles array
  54421. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  54422. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  54423. };
  54424. /**
  54425. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54426. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54427. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54428. * `nb` (positive integer) the number of particles to be created from this model
  54429. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54430. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54431. */
  54432. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54433. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54434. var meshInd = mesh.getIndices();
  54435. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54436. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54437. var shape = this._posToShape(meshPos);
  54438. var shapeUV = this._uvsToShapeUV(meshUV);
  54439. var posfunc = options ? options.positionFunction : null;
  54440. var vtxfunc = options ? options.vertexFunction : null;
  54441. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54442. // particles
  54443. var idx = this.nbParticles;
  54444. for (var i = 0; i < nb; i++) {
  54445. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  54446. if (this._updatable) {
  54447. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  54448. }
  54449. this._index += shape.length;
  54450. idx++;
  54451. }
  54452. this.nbParticles += nb;
  54453. this._shapeCounter++;
  54454. return this._shapeCounter - 1;
  54455. };
  54456. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54457. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54458. this._resetCopy();
  54459. if (particle._model._positionFunction) {
  54460. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54461. }
  54462. if (this._copy.rotationQuaternion) {
  54463. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54464. }
  54465. else {
  54466. this._yaw = this._copy.rotation.y;
  54467. this._pitch = this._copy.rotation.x;
  54468. this._roll = this._copy.rotation.z;
  54469. this._quaternionRotationYPR();
  54470. }
  54471. this._quaternionToRotationMatrix();
  54472. this._shape = particle._model._shape;
  54473. for (var pt = 0; pt < this._shape.length; pt++) {
  54474. this._vertex.x = this._shape[pt].x;
  54475. this._vertex.y = this._shape[pt].y;
  54476. this._vertex.z = this._shape[pt].z;
  54477. if (particle._model._vertexFunction) {
  54478. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54479. }
  54480. this._vertex.x *= this._copy.scaling.x;
  54481. this._vertex.y *= this._copy.scaling.y;
  54482. this._vertex.z *= this._copy.scaling.z;
  54483. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54484. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54485. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54486. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54487. }
  54488. particle.position.x = 0;
  54489. particle.position.y = 0;
  54490. particle.position.z = 0;
  54491. particle.rotation.x = 0;
  54492. particle.rotation.y = 0;
  54493. particle.rotation.z = 0;
  54494. particle.rotationQuaternion = null;
  54495. particle.scaling.x = 1;
  54496. particle.scaling.y = 1;
  54497. particle.scaling.z = 1;
  54498. };
  54499. /**
  54500. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54501. */
  54502. SolidParticleSystem.prototype.rebuildMesh = function () {
  54503. for (var p = 0; p < this.particles.length; p++) {
  54504. this._rebuildParticle(this.particles[p]);
  54505. }
  54506. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54507. };
  54508. /**
  54509. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54510. * This method calls `updateParticle()` for each particle of the SPS.
  54511. * For an animated SPS, it is usually called within the render loop.
  54512. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54513. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54514. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54515. */
  54516. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54517. if (start === void 0) { start = 0; }
  54518. if (end === void 0) { end = this.nbParticles - 1; }
  54519. if (update === void 0) { update = true; }
  54520. if (!this._updatable) {
  54521. return;
  54522. }
  54523. // custom beforeUpdate
  54524. this.beforeUpdateParticles(start, end, update);
  54525. this._cam_axisX.x = 1;
  54526. this._cam_axisX.y = 0;
  54527. this._cam_axisX.z = 0;
  54528. this._cam_axisY.x = 0;
  54529. this._cam_axisY.y = 1;
  54530. this._cam_axisY.z = 0;
  54531. this._cam_axisZ.x = 0;
  54532. this._cam_axisZ.y = 0;
  54533. this._cam_axisZ.z = 1;
  54534. // if the particles will always face the camera
  54535. if (this.billboard) {
  54536. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  54537. this._yaw = this.mesh.rotation.y;
  54538. this._pitch = this.mesh.rotation.x;
  54539. this._roll = this.mesh.rotation.z;
  54540. this._quaternionRotationYPR();
  54541. this._quaternionToRotationMatrix();
  54542. this._rotMatrix.invertToRef(this._invertMatrix);
  54543. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  54544. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  54545. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  54546. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  54547. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  54548. this._cam_axisY.normalize();
  54549. this._cam_axisX.normalize();
  54550. this._cam_axisZ.normalize();
  54551. }
  54552. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54553. var idx = 0;
  54554. var index = 0;
  54555. var colidx = 0;
  54556. var colorIndex = 0;
  54557. var uvidx = 0;
  54558. var uvIndex = 0;
  54559. var pt = 0;
  54560. if (this._computeBoundingBox) {
  54561. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54562. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54563. }
  54564. // particle loop
  54565. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  54566. for (var p = start; p <= end; p++) {
  54567. this._particle = this.particles[p];
  54568. this._shape = this._particle._model._shape;
  54569. this._shapeUV = this._particle._model._shapeUV;
  54570. // call to custom user function to update the particle properties
  54571. this.updateParticle(this._particle);
  54572. if (this._particle.isVisible) {
  54573. // particle rotation matrix
  54574. if (this.billboard) {
  54575. this._particle.rotation.x = 0.0;
  54576. this._particle.rotation.y = 0.0;
  54577. }
  54578. if (this._computeParticleRotation) {
  54579. if (this._particle.rotationQuaternion) {
  54580. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54581. }
  54582. else {
  54583. this._yaw = this._particle.rotation.y;
  54584. this._pitch = this._particle.rotation.x;
  54585. this._roll = this._particle.rotation.z;
  54586. this._quaternionRotationYPR();
  54587. }
  54588. this._quaternionToRotationMatrix();
  54589. }
  54590. // particle vertex loop
  54591. for (pt = 0; pt < this._shape.length; pt++) {
  54592. idx = index + pt * 3;
  54593. colidx = colorIndex + pt * 4;
  54594. uvidx = uvIndex + pt * 2;
  54595. this._vertex.x = this._shape[pt].x;
  54596. this._vertex.y = this._shape[pt].y;
  54597. this._vertex.z = this._shape[pt].z;
  54598. if (this._computeParticleVertex) {
  54599. this.updateParticleVertex(this._particle, this._vertex, pt);
  54600. }
  54601. // positions
  54602. this._vertex.x *= this._particle.scaling.x;
  54603. this._vertex.y *= this._particle.scaling.y;
  54604. this._vertex.z *= this._particle.scaling.z;
  54605. 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];
  54606. 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;
  54607. 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;
  54608. 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;
  54609. 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;
  54610. 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;
  54611. 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;
  54612. if (this._computeBoundingBox) {
  54613. if (this._positions32[idx] < this._minimum.x) {
  54614. this._minimum.x = this._positions32[idx];
  54615. }
  54616. if (this._positions32[idx] > this._maximum.x) {
  54617. this._maximum.x = this._positions32[idx];
  54618. }
  54619. if (this._positions32[idx + 1] < this._minimum.y) {
  54620. this._minimum.y = this._positions32[idx + 1];
  54621. }
  54622. if (this._positions32[idx + 1] > this._maximum.y) {
  54623. this._maximum.y = this._positions32[idx + 1];
  54624. }
  54625. if (this._positions32[idx + 2] < this._minimum.z) {
  54626. this._minimum.z = this._positions32[idx + 2];
  54627. }
  54628. if (this._positions32[idx + 2] > this._maximum.z) {
  54629. this._maximum.z = this._positions32[idx + 2];
  54630. }
  54631. }
  54632. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  54633. if (!this._computeParticleVertex && !this.billboard) {
  54634. this._normal.x = this._fixedNormal32[idx];
  54635. this._normal.y = this._fixedNormal32[idx + 1];
  54636. this._normal.z = this._fixedNormal32[idx + 2];
  54637. 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];
  54638. 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;
  54639. 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;
  54640. 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;
  54641. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54642. 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;
  54643. 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;
  54644. }
  54645. if (this._computeParticleColor) {
  54646. this._colors32[colidx] = this._particle.color.r;
  54647. this._colors32[colidx + 1] = this._particle.color.g;
  54648. this._colors32[colidx + 2] = this._particle.color.b;
  54649. this._colors32[colidx + 3] = this._particle.color.a;
  54650. }
  54651. if (this._computeParticleTexture) {
  54652. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54653. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54654. }
  54655. }
  54656. }
  54657. else {
  54658. for (pt = 0; pt < this._shape.length; pt++) {
  54659. idx = index + pt * 3;
  54660. colidx = colorIndex + pt * 4;
  54661. uvidx = uvIndex + pt * 2;
  54662. this._positions32[idx] = this._camera.position.x;
  54663. this._positions32[idx + 1] = this._camera.position.y;
  54664. this._positions32[idx + 2] = this._camera.position.z;
  54665. this._normals32[idx] = 0.0;
  54666. this._normals32[idx + 1] = 0.0;
  54667. this._normals32[idx + 2] = 0.0;
  54668. if (this._computeParticleColor) {
  54669. this._colors32[colidx] = this._particle.color.r;
  54670. this._colors32[colidx + 1] = this._particle.color.g;
  54671. this._colors32[colidx + 2] = this._particle.color.b;
  54672. this._colors32[colidx + 3] = this._particle.color.a;
  54673. }
  54674. if (this._computeParticleTexture) {
  54675. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54676. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54677. }
  54678. }
  54679. }
  54680. // increment indexes for the next particle
  54681. index = idx + 3;
  54682. colorIndex = colidx + 4;
  54683. uvIndex = uvidx + 2;
  54684. }
  54685. // if the VBO must be updated
  54686. if (update) {
  54687. if (this._computeParticleColor) {
  54688. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54689. }
  54690. if (this._computeParticleTexture) {
  54691. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54692. }
  54693. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54694. if (!this.mesh.areNormalsFrozen) {
  54695. if (this._computeParticleVertex || this.billboard) {
  54696. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54697. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  54698. for (var i = 0; i < this._normals32.length; i++) {
  54699. this._fixedNormal32[i] = this._normals32[i];
  54700. }
  54701. }
  54702. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54703. }
  54704. }
  54705. if (this._computeBoundingBox) {
  54706. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54707. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54708. }
  54709. this.afterUpdateParticles(start, end, update);
  54710. };
  54711. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54712. this._halfroll = this._roll * 0.5;
  54713. this._halfpitch = this._pitch * 0.5;
  54714. this._halfyaw = this._yaw * 0.5;
  54715. this._sinRoll = Math.sin(this._halfroll);
  54716. this._cosRoll = Math.cos(this._halfroll);
  54717. this._sinPitch = Math.sin(this._halfpitch);
  54718. this._cosPitch = Math.cos(this._halfpitch);
  54719. this._sinYaw = Math.sin(this._halfyaw);
  54720. this._cosYaw = Math.cos(this._halfyaw);
  54721. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54722. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54723. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54724. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54725. };
  54726. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54727. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54728. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54729. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54730. this._rotMatrix.m[3] = 0;
  54731. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54732. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54733. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54734. this._rotMatrix.m[7] = 0;
  54735. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54736. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54737. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54738. this._rotMatrix.m[11] = 0;
  54739. this._rotMatrix.m[12] = 0;
  54740. this._rotMatrix.m[13] = 0;
  54741. this._rotMatrix.m[14] = 0;
  54742. this._rotMatrix.m[15] = 1.0;
  54743. };
  54744. /**
  54745. * Disposes the SPS
  54746. */
  54747. SolidParticleSystem.prototype.dispose = function () {
  54748. this.mesh.dispose();
  54749. this.vars = null;
  54750. // drop references to internal big arrays for the GC
  54751. this._positions = null;
  54752. this._indices = null;
  54753. this._normals = null;
  54754. this._uvs = null;
  54755. this._colors = null;
  54756. this._positions32 = null;
  54757. this._normals32 = null;
  54758. this._fixedNormal32 = null;
  54759. this._uvs32 = null;
  54760. this._colors32 = null;
  54761. this.pickedParticles = null;
  54762. };
  54763. /**
  54764. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54765. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54766. */
  54767. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54768. if (!this._isVisibilityBoxLocked) {
  54769. this.mesh.refreshBoundingInfo();
  54770. }
  54771. };
  54772. /**
  54773. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54774. * @param size the size (float) of the visibility box
  54775. * note : this doesn't lock the SPS mesh bounding box.
  54776. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54777. */
  54778. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54779. var vis = size / 2;
  54780. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54781. };
  54782. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54783. // getter and setter
  54784. get: function () {
  54785. return this._alwaysVisible;
  54786. },
  54787. /**
  54788. * Sets the SPS as always visible or not
  54789. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54790. */
  54791. set: function (val) {
  54792. this._alwaysVisible = val;
  54793. this.mesh.alwaysSelectAsActiveMesh = val;
  54794. },
  54795. enumerable: true,
  54796. configurable: true
  54797. });
  54798. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54799. get: function () {
  54800. return this._isVisibilityBoxLocked;
  54801. },
  54802. /**
  54803. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54804. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54805. */
  54806. set: function (val) {
  54807. this._isVisibilityBoxLocked = val;
  54808. this.mesh.getBoundingInfo().isLocked = val;
  54809. },
  54810. enumerable: true,
  54811. configurable: true
  54812. });
  54813. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54814. // getters
  54815. get: function () {
  54816. return this._computeParticleRotation;
  54817. },
  54818. // Optimizer setters
  54819. /**
  54820. * Tells to `setParticles()` to compute the particle rotations or not.
  54821. * Default value : true. The SPS is faster when it's set to false.
  54822. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54823. */
  54824. set: function (val) {
  54825. this._computeParticleRotation = val;
  54826. },
  54827. enumerable: true,
  54828. configurable: true
  54829. });
  54830. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54831. get: function () {
  54832. return this._computeParticleColor;
  54833. },
  54834. /**
  54835. * Tells to `setParticles()` to compute the particle colors or not.
  54836. * Default value : true. The SPS is faster when it's set to false.
  54837. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54838. */
  54839. set: function (val) {
  54840. this._computeParticleColor = val;
  54841. },
  54842. enumerable: true,
  54843. configurable: true
  54844. });
  54845. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54846. get: function () {
  54847. return this._computeParticleTexture;
  54848. },
  54849. /**
  54850. * Tells to `setParticles()` to compute the particle textures or not.
  54851. * Default value : true. The SPS is faster when it's set to false.
  54852. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54853. */
  54854. set: function (val) {
  54855. this._computeParticleTexture = val;
  54856. },
  54857. enumerable: true,
  54858. configurable: true
  54859. });
  54860. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54861. get: function () {
  54862. return this._computeParticleVertex;
  54863. },
  54864. /**
  54865. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54866. * Default value : false. The SPS is faster when it's set to false.
  54867. * Note : the particle custom vertex positions aren't stored values.
  54868. */
  54869. set: function (val) {
  54870. this._computeParticleVertex = val;
  54871. },
  54872. enumerable: true,
  54873. configurable: true
  54874. });
  54875. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54876. get: function () {
  54877. return this._computeBoundingBox;
  54878. },
  54879. /**
  54880. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54881. */
  54882. set: function (val) {
  54883. this._computeBoundingBox = val;
  54884. },
  54885. enumerable: true,
  54886. configurable: true
  54887. });
  54888. // =======================================================================
  54889. // Particle behavior logic
  54890. // these following methods may be overwritten by the user to fit his needs
  54891. /**
  54892. * This function does nothing. It may be overwritten to set all the particle first values.
  54893. * The SPS doesn't call this function, you may have to call it by your own.
  54894. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54895. */
  54896. SolidParticleSystem.prototype.initParticles = function () {
  54897. };
  54898. /**
  54899. * This function does nothing. It may be overwritten to recycle a particle.
  54900. * The SPS doesn't call this function, you may have to call it by your own.
  54901. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54902. */
  54903. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54904. return particle;
  54905. };
  54906. /**
  54907. * Updates a particle : this function should be overwritten by the user.
  54908. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54909. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54910. * ex : just set a particle position or velocity and recycle conditions
  54911. */
  54912. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54913. return particle;
  54914. };
  54915. /**
  54916. * Updates a vertex of a particle : it can be overwritten by the user.
  54917. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54918. * @param particle the current particle
  54919. * @param vertex the current index of the current particle
  54920. * @param pt the index of the current vertex in the particle shape
  54921. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54922. * ex : just set a vertex particle position
  54923. */
  54924. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54925. return vertex;
  54926. };
  54927. /**
  54928. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54929. * This does nothing and may be overwritten by the user.
  54930. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54931. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54932. * @param update the boolean update value actually passed to setParticles()
  54933. */
  54934. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54935. };
  54936. /**
  54937. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54938. * This will be passed three parameters.
  54939. * This does nothing and may be overwritten by the user.
  54940. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54941. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54942. * @param update the boolean update value actually passed to setParticles()
  54943. */
  54944. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54945. };
  54946. return SolidParticleSystem;
  54947. })();
  54948. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54949. })(BABYLON || (BABYLON = {}));
  54950. var BABYLON;
  54951. (function (BABYLON) {
  54952. var Internals;
  54953. (function (Internals) {
  54954. var FileFaceOrientation = (function () {
  54955. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54956. this.name = name;
  54957. this.worldAxisForNormal = worldAxisForNormal;
  54958. this.worldAxisForFileX = worldAxisForFileX;
  54959. this.worldAxisForFileY = worldAxisForFileY;
  54960. }
  54961. return FileFaceOrientation;
  54962. })();
  54963. ;
  54964. /**
  54965. * Helper class dealing with the extraction of spherical polynomial dataArray
  54966. * from a cube map.
  54967. */
  54968. var CubeMapToSphericalPolynomialTools = (function () {
  54969. function CubeMapToSphericalPolynomialTools() {
  54970. }
  54971. /**
  54972. * Converts a cubemap to the according Spherical Polynomial data.
  54973. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54974. *
  54975. * @param cubeInfo The Cube map to extract the information from.
  54976. * @return The Spherical Polynomial data.
  54977. */
  54978. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54979. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54980. var totalSolidAngle = 0.0;
  54981. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54982. var du = 2.0 / cubeInfo.size;
  54983. var dv = du;
  54984. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54985. var minUV = du * 0.5 - 1.0;
  54986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54987. var fileFace = this.FileFaces[faceIndex];
  54988. var dataArray = cubeInfo[fileFace.name];
  54989. var v = minUV;
  54990. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54991. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54992. // Because SP is still linear, so summation is fine in that basis.
  54993. for (var y = 0; y < cubeInfo.size; y++) {
  54994. var u = minUV;
  54995. for (var x = 0; x < cubeInfo.size; x++) {
  54996. // World direction (not normalised)
  54997. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54998. worldDirection.normalize();
  54999. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55000. if (1) {
  55001. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  55002. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  55003. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  55004. var color = new BABYLON.Color3(r, g, b);
  55005. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55006. }
  55007. else {
  55008. if (faceIndex == 0) {
  55009. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55010. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55011. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55012. }
  55013. else if (faceIndex == 1) {
  55014. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55015. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55016. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55017. }
  55018. else if (faceIndex == 2) {
  55019. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55020. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55021. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55022. }
  55023. else if (faceIndex == 3) {
  55024. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55025. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55026. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55027. }
  55028. else if (faceIndex == 4) {
  55029. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55030. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55031. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55032. }
  55033. else if (faceIndex == 5) {
  55034. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55037. }
  55038. 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]);
  55039. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55040. }
  55041. totalSolidAngle += deltaSolidAngle;
  55042. u += du;
  55043. }
  55044. v += dv;
  55045. }
  55046. }
  55047. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  55048. var correction = correctSolidAngle / totalSolidAngle;
  55049. sphericalHarmonics.scale(correction);
  55050. // Additionally scale by pi -- audit needed
  55051. sphericalHarmonics.scale(1.0 / Math.PI);
  55052. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55053. };
  55054. CubeMapToSphericalPolynomialTools.FileFaces = [
  55055. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55056. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55057. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55058. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55059. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55060. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55061. ];
  55062. return CubeMapToSphericalPolynomialTools;
  55063. })();
  55064. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55065. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55066. })(BABYLON || (BABYLON = {}));
  55067. var BABYLON;
  55068. (function (BABYLON) {
  55069. var Internals;
  55070. (function (Internals) {
  55071. /**
  55072. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55073. */
  55074. var PanoramaToCubeMapTools = (function () {
  55075. function PanoramaToCubeMapTools() {
  55076. }
  55077. /**
  55078. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55079. *
  55080. * @param float32Array The source data.
  55081. * @param inputWidth The width of the input panorama.
  55082. * @param inputhHeight The height of the input panorama.
  55083. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55084. * @return The cubemap data
  55085. */
  55086. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55087. if (!float32Array) {
  55088. throw "ConvertPanoramaToCubemap: input cannot be null";
  55089. }
  55090. if (float32Array.length != inputWidth * inputHeight * 3) {
  55091. throw "ConvertPanoramaToCubemap: input size is wrong";
  55092. }
  55093. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55094. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55095. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55096. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55097. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55098. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55099. return {
  55100. front: textureFront,
  55101. back: textureBack,
  55102. left: textureLeft,
  55103. right: textureRight,
  55104. up: textureUp,
  55105. down: textureDown,
  55106. size: size
  55107. };
  55108. };
  55109. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55110. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55111. var textureArray = new Float32Array(buffer);
  55112. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55113. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55114. var dy = 1 / texSize;
  55115. var fy = 0;
  55116. for (var y = 0; y < texSize; y++) {
  55117. var xv1 = faceData[0];
  55118. var xv2 = faceData[2];
  55119. for (var x = 0; x < texSize; x++) {
  55120. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55121. v.normalize();
  55122. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55123. // 3 channels per pixels
  55124. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55125. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55126. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55127. xv1 = xv1.add(rotDX1);
  55128. xv2 = xv2.add(rotDX2);
  55129. }
  55130. fy += dy;
  55131. }
  55132. return textureArray;
  55133. };
  55134. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55135. var theta = Math.atan2(vDir.z, vDir.x);
  55136. var phi = Math.acos(vDir.y);
  55137. while (theta < -Math.PI)
  55138. theta += 2 * Math.PI;
  55139. while (theta > Math.PI)
  55140. theta -= 2 * Math.PI;
  55141. var dx = theta / Math.PI;
  55142. var dy = phi / Math.PI;
  55143. // recenter.
  55144. dx = dx * 0.5 + 0.5;
  55145. var px = Math.round(dx * inputWidth);
  55146. if (px < 0)
  55147. px = 0;
  55148. else if (px >= inputWidth)
  55149. px = inputWidth - 1;
  55150. var py = Math.round(dy * inputHeight);
  55151. if (py < 0)
  55152. py = 0;
  55153. else if (py >= inputHeight)
  55154. py = inputHeight - 1;
  55155. var inputY = (inputHeight - py - 1);
  55156. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55157. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55158. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55159. return {
  55160. r: r,
  55161. g: g,
  55162. b: b
  55163. };
  55164. };
  55165. PanoramaToCubeMapTools.FACE_FRONT = [
  55166. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55167. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55168. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55169. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55170. ];
  55171. PanoramaToCubeMapTools.FACE_BACK = [
  55172. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55173. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55174. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55175. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55176. ];
  55177. PanoramaToCubeMapTools.FACE_RIGHT = [
  55178. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55179. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55180. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55181. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55182. ];
  55183. PanoramaToCubeMapTools.FACE_LEFT = [
  55184. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55185. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55186. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55187. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55188. ];
  55189. PanoramaToCubeMapTools.FACE_DOWN = [
  55190. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55191. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55192. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55193. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55194. ];
  55195. PanoramaToCubeMapTools.FACE_UP = [
  55196. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55197. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55198. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55199. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55200. ];
  55201. return PanoramaToCubeMapTools;
  55202. })();
  55203. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55204. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55205. })(BABYLON || (BABYLON = {}));
  55206. var BABYLON;
  55207. (function (BABYLON) {
  55208. var Internals;
  55209. (function (Internals) {
  55210. ;
  55211. /**
  55212. * This groups tools to convert HDR texture to native colors array.
  55213. */
  55214. var HDRTools = (function () {
  55215. function HDRTools() {
  55216. }
  55217. HDRTools.Ldexp = function (mantissa, exponent) {
  55218. if (exponent > 1023) {
  55219. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55220. }
  55221. if (exponent < -1074) {
  55222. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55223. }
  55224. return mantissa * Math.pow(2, exponent);
  55225. };
  55226. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55227. if (exponent > 0) {
  55228. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55229. float32array[index + 0] = red * exponent;
  55230. float32array[index + 1] = green * exponent;
  55231. float32array[index + 2] = blue * exponent;
  55232. }
  55233. else {
  55234. float32array[index + 0] = 0;
  55235. float32array[index + 1] = 0;
  55236. float32array[index + 2] = 0;
  55237. }
  55238. };
  55239. HDRTools.readStringLine = function (uint8array, startIndex) {
  55240. var line = "";
  55241. var character = "";
  55242. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55243. character = String.fromCharCode(uint8array[i]);
  55244. if (character == "\n") {
  55245. break;
  55246. }
  55247. line += character;
  55248. }
  55249. return line;
  55250. };
  55251. /**
  55252. * Reads header information from an RGBE texture stored in a native array.
  55253. * More information on this format are available here:
  55254. * https://en.wikipedia.org/wiki/RGBE_image_format
  55255. *
  55256. * @param uint8array The binary file stored in native array.
  55257. * @return The header information.
  55258. */
  55259. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55260. var height = 0;
  55261. var width = 0;
  55262. var line = this.readStringLine(uint8array, 0);
  55263. if (line[0] != '#' || line[1] != '?') {
  55264. throw "Bad HDR Format.";
  55265. }
  55266. var endOfHeader = false;
  55267. var findFormat = false;
  55268. var lineIndex = 0;
  55269. do {
  55270. lineIndex += (line.length + 1);
  55271. line = this.readStringLine(uint8array, lineIndex);
  55272. if (line == "FORMAT=32-bit_rle_rgbe") {
  55273. findFormat = true;
  55274. }
  55275. else if (line.length == 0) {
  55276. endOfHeader = true;
  55277. }
  55278. } while (!endOfHeader);
  55279. if (!findFormat) {
  55280. throw "HDR Bad header format, unsupported FORMAT";
  55281. }
  55282. lineIndex += (line.length + 1);
  55283. line = this.readStringLine(uint8array, lineIndex);
  55284. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55285. var match = sizeRegexp.exec(line);
  55286. // TODO. Support +Y and -X if needed.
  55287. if (match.length < 3) {
  55288. throw "HDR Bad header format, no size";
  55289. }
  55290. width = parseInt(match[2]);
  55291. height = parseInt(match[1]);
  55292. if (width < 8 || width > 0x7fff) {
  55293. throw "HDR Bad header format, unsupported size";
  55294. }
  55295. lineIndex += (line.length + 1);
  55296. return {
  55297. height: height,
  55298. width: width,
  55299. dataPosition: lineIndex
  55300. };
  55301. };
  55302. /**
  55303. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55304. * This RGBE texture needs to store the information as a panorama.
  55305. *
  55306. * More information on this format are available here:
  55307. * https://en.wikipedia.org/wiki/RGBE_image_format
  55308. *
  55309. * @param buffer The binary file stored in an array buffer.
  55310. * @param size The expected size of the extracted cubemap.
  55311. * @return The Cube Map information.
  55312. */
  55313. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55314. var uint8array = new Uint8Array(buffer);
  55315. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55316. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55317. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55318. return cubeMapData;
  55319. };
  55320. /**
  55321. * Returns the pixels data extracted from an RGBE texture.
  55322. * This pixels will be stored left to right up to down in the R G B order in one array.
  55323. *
  55324. * More information on this format are available here:
  55325. * https://en.wikipedia.org/wiki/RGBE_image_format
  55326. *
  55327. * @param uint8array The binary file stored in an array buffer.
  55328. * @param hdrInfo The header information of the file.
  55329. * @return The pixels data in RGB right to left up to down order.
  55330. */
  55331. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55332. // Keep for multi format supports.
  55333. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55334. };
  55335. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55336. var num_scanlines = hdrInfo.height;
  55337. var scanline_width = hdrInfo.width;
  55338. var a, b, c, d, count;
  55339. var dataIndex = hdrInfo.dataPosition;
  55340. var index = 0, endIndex = 0, i = 0;
  55341. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55342. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55343. // 3 channels of 4 bytes per pixel in float.
  55344. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55345. var resultArray = new Float32Array(resultBuffer);
  55346. // read in each successive scanline
  55347. while (num_scanlines > 0) {
  55348. a = uint8array[dataIndex++];
  55349. b = uint8array[dataIndex++];
  55350. c = uint8array[dataIndex++];
  55351. d = uint8array[dataIndex++];
  55352. if (a != 2 || b != 2 || (c & 0x80)) {
  55353. // this file is not run length encoded
  55354. throw "HDR Bad header format, not RLE";
  55355. }
  55356. if (((c << 8) | d) != scanline_width) {
  55357. throw "HDR Bad header format, wrong scan line width";
  55358. }
  55359. index = 0;
  55360. // read each of the four channels for the scanline into the buffer
  55361. for (i = 0; i < 4; i++) {
  55362. endIndex = (i + 1) * scanline_width;
  55363. while (index < endIndex) {
  55364. a = uint8array[dataIndex++];
  55365. b = uint8array[dataIndex++];
  55366. if (a > 128) {
  55367. // a run of the same value
  55368. count = a - 128;
  55369. if ((count == 0) || (count > endIndex - index)) {
  55370. throw "HDR Bad Format, bad scanline data (run)";
  55371. }
  55372. while (count-- > 0) {
  55373. scanLineArray[index++] = b;
  55374. }
  55375. }
  55376. else {
  55377. // a non-run
  55378. count = a;
  55379. if ((count == 0) || (count > endIndex - index)) {
  55380. throw "HDR Bad Format, bad scanline data (non-run)";
  55381. }
  55382. scanLineArray[index++] = b;
  55383. if (--count > 0) {
  55384. for (var j = 0; j < count; j++) {
  55385. scanLineArray[index++] = uint8array[dataIndex++];
  55386. }
  55387. }
  55388. }
  55389. }
  55390. }
  55391. // now convert data from buffer into floats
  55392. for (i = 0; i < scanline_width; i++) {
  55393. a = scanLineArray[i];
  55394. b = scanLineArray[i + scanline_width];
  55395. c = scanLineArray[i + 2 * scanline_width];
  55396. d = scanLineArray[i + 3 * scanline_width];
  55397. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55398. }
  55399. num_scanlines--;
  55400. }
  55401. return resultArray;
  55402. };
  55403. return HDRTools;
  55404. })();
  55405. Internals.HDRTools = HDRTools;
  55406. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55407. })(BABYLON || (BABYLON = {}));
  55408. //_______________________________________________________________
  55409. // Extracted from CubeMapGen:
  55410. // https://code.google.com/archive/p/cubemapgen/
  55411. //
  55412. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55413. //_______________________________________________________________
  55414. var BABYLON;
  55415. (function (BABYLON) {
  55416. var Internals;
  55417. (function (Internals) {
  55418. /**
  55419. * The bounding box information used during the conversion process.
  55420. */
  55421. var CMGBoundinBox = (function () {
  55422. function CMGBoundinBox() {
  55423. this.min = new BABYLON.Vector3(0, 0, 0);
  55424. this.max = new BABYLON.Vector3(0, 0, 0);
  55425. this.clear();
  55426. }
  55427. CMGBoundinBox.prototype.clear = function () {
  55428. this.min.x = CMGBoundinBox.MAX;
  55429. this.min.y = CMGBoundinBox.MAX;
  55430. this.min.z = CMGBoundinBox.MAX;
  55431. this.max.x = CMGBoundinBox.MIN;
  55432. this.max.y = CMGBoundinBox.MIN;
  55433. this.max.z = CMGBoundinBox.MIN;
  55434. };
  55435. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55436. this.min.x = Math.min(this.min.x, x);
  55437. this.min.y = Math.min(this.min.y, y);
  55438. this.min.z = Math.min(this.min.z, z);
  55439. this.max.x = Math.max(this.max.x, x);
  55440. this.max.y = Math.max(this.max.y, y);
  55441. this.max.z = Math.max(this.max.z, z);
  55442. };
  55443. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55444. this.min.x = Math.max(this.min.x, x);
  55445. this.min.y = Math.max(this.min.y, y);
  55446. this.min.z = Math.max(this.min.z, z);
  55447. };
  55448. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55449. this.max.x = Math.min(this.max.x, x);
  55450. this.max.y = Math.min(this.max.y, y);
  55451. this.max.z = Math.min(this.max.z, z);
  55452. };
  55453. CMGBoundinBox.prototype.empty = function () {
  55454. if ((this.min.x > this.max.y) ||
  55455. (this.min.y > this.max.y) ||
  55456. (this.min.z > this.max.y)) {
  55457. return true;
  55458. }
  55459. else {
  55460. return false;
  55461. }
  55462. };
  55463. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55464. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55465. return CMGBoundinBox;
  55466. })();
  55467. /**
  55468. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55469. * required by the glossinees of a material.
  55470. *
  55471. * This only supports the cosine drop power as well as Warp fixup generation method.
  55472. *
  55473. * This is using the process from CubeMapGen described here:
  55474. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55475. */
  55476. var PMREMGenerator = (function () {
  55477. /**
  55478. * Constructor of the generator.
  55479. *
  55480. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55481. * @param inputSize The size of the cubemap faces
  55482. * @param outputSize The size of the output cubemap faces
  55483. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55484. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55485. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55486. * @param specularPower The max specular level of the desired cubemap
  55487. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55488. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55489. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55490. */
  55491. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55492. this.input = input;
  55493. this.inputSize = inputSize;
  55494. this.outputSize = outputSize;
  55495. this.maxNumMipLevels = maxNumMipLevels;
  55496. this.numChannels = numChannels;
  55497. this.isFloat = isFloat;
  55498. this.specularPower = specularPower;
  55499. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55500. this.excludeBase = excludeBase;
  55501. this.fixup = fixup;
  55502. this._outputSurface = [];
  55503. this._numMipLevels = 0;
  55504. }
  55505. /**
  55506. * Launches the filter process and return the result.
  55507. *
  55508. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55509. */
  55510. PMREMGenerator.prototype.filterCubeMap = function () {
  55511. // Init cubemap processor
  55512. this.init();
  55513. // Filters the cubemap
  55514. this.filterCubeMapMipChain();
  55515. // Returns the filtered mips.
  55516. return this._outputSurface;
  55517. };
  55518. PMREMGenerator.prototype.init = function () {
  55519. var i;
  55520. var j;
  55521. var mipLevelSize;
  55522. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55523. if (this.maxNumMipLevels == 0) {
  55524. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55525. }
  55526. //first miplevel size
  55527. mipLevelSize = this.outputSize;
  55528. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55529. for (j = 0; j < this.maxNumMipLevels; j++) {
  55530. this._outputSurface.length++;
  55531. this._outputSurface[j] = [];
  55532. //Iterate over faces for output images
  55533. for (i = 0; i < 6; i++) {
  55534. this._outputSurface[j].length++;
  55535. // Initializes a new array for the output.
  55536. if (this.isFloat) {
  55537. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55538. }
  55539. else {
  55540. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55541. }
  55542. }
  55543. //next mip level is half size
  55544. mipLevelSize >>= 1;
  55545. this._numMipLevels++;
  55546. //terminate if mip chain becomes too small
  55547. if (mipLevelSize == 0) {
  55548. this.maxNumMipLevels = j;
  55549. return;
  55550. }
  55551. }
  55552. };
  55553. //--------------------------------------------------------------------------------------
  55554. //Cube map filtering and mip chain generation.
  55555. // the cube map filtereing is specified using a number of parameters:
  55556. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55557. // indicates the region of the hemisphere to filter over for each tap.
  55558. //
  55559. // Note that the top mip level is also a filtered version of the original input images
  55560. // as well in order to create mip chains for diffuse environment illumination.
  55561. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55562. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55563. //
  55564. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55565. // is a_InitialMipAngle
  55566. //
  55567. // The angle for the subsequent levels of the mip chain are specified by their parents
  55568. // filtering angle and a per-level scale and bias
  55569. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55570. //
  55571. //--------------------------------------------------------------------------------------
  55572. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55573. // First, take count of the lighting model to modify SpecularPower
  55574. // 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;
  55575. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55576. //Cone angle start (for generating subsequent mip levels)
  55577. var currentSpecularPower = this.specularPower;
  55578. //Build filter lookup tables based on the source miplevel size
  55579. this.precomputeFilterLookupTables(this.inputSize);
  55580. // Note that we need to filter the first level before generating mipmap
  55581. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55582. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55583. // TODO : Write a function to copy and scale the base mipmap in output
  55584. // I am just lazy here and just put a high specular power value, and do some if.
  55585. if (this.excludeBase && (levelIndex == 0)) {
  55586. // 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).
  55587. currentSpecularPower = 100000.0;
  55588. }
  55589. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55590. var srcCubeImage = this.input;
  55591. var dstCubeImage = this._outputSurface[levelIndex];
  55592. var dstSize = this.outputSize >> levelIndex;
  55593. // Compute required angle.
  55594. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55595. // filter cube surfaces
  55596. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55597. // fix seams
  55598. if (this.fixup) {
  55599. this.fixupCubeEdges(dstCubeImage, dstSize);
  55600. }
  55601. // Decrease the specular power to generate the mipmap chain
  55602. // TODO : Use another method for Exclude (see first comment at start of the function
  55603. if (this.excludeBase && (levelIndex == 0)) {
  55604. currentSpecularPower = this.specularPower;
  55605. }
  55606. currentSpecularPower *= this.cosinePowerDropPerMip;
  55607. }
  55608. };
  55609. //--------------------------------------------------------------------------------------
  55610. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55611. // It allow to optimize the texel to access base on the specular power.
  55612. //--------------------------------------------------------------------------------------
  55613. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55614. // We want to find the alpha such that:
  55615. // cos(alpha)^cosinePower = epsilon
  55616. // That's: acos(epsilon^(1/cosinePower))
  55617. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55618. var angle = 180.0;
  55619. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55620. angle *= 180.0 / Math.PI; // Convert to degree
  55621. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55622. return angle;
  55623. };
  55624. //--------------------------------------------------------------------------------------
  55625. //Builds the following lookup tables prior to filtering:
  55626. // -normalizer cube map
  55627. // -tap weight lookup table
  55628. //
  55629. //--------------------------------------------------------------------------------------
  55630. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55631. var srcTexelAngle;
  55632. var iCubeFace;
  55633. //clear pre-existing normalizer cube map
  55634. this._normCubeMap = [];
  55635. //Normalized vectors per cubeface and per-texel solid angle
  55636. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55637. };
  55638. //--------------------------------------------------------------------------------------
  55639. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55640. //
  55641. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55642. //
  55643. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55644. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55645. // below
  55646. //--------------------------------------------------------------------------------------
  55647. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55648. var iCubeFace;
  55649. var u;
  55650. var v;
  55651. //iterate over cube faces
  55652. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55653. //First three channels for norm cube, and last channel for solid angle
  55654. this._normCubeMap.push(new Float32Array(size * size * 4));
  55655. //fast texture walk, build normalizer cube map
  55656. var facesData = this.input[iCubeFace];
  55657. for (v = 0; v < size; v++) {
  55658. for (u = 0; u < size; u++) {
  55659. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55660. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55661. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55662. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55663. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55664. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55665. }
  55666. }
  55667. }
  55668. };
  55669. //--------------------------------------------------------------------------------------
  55670. // Convert cubemap face texel coordinates and face idx to 3D vector
  55671. // note the U and V coords are integer coords and range from 0 to size-1
  55672. // this routine can be used to generate a normalizer cube map
  55673. //--------------------------------------------------------------------------------------
  55674. // SL BEGIN
  55675. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55676. var nvcU;
  55677. var nvcV;
  55678. var tempVec;
  55679. // Change from original AMD code
  55680. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55681. // + 0.5f is for texel center addressing
  55682. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55683. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55684. // warp fixup
  55685. if (fixup && size > 1) {
  55686. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55687. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55688. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55689. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55690. }
  55691. // Get current vector
  55692. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55693. // U contribution
  55694. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55695. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55696. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55697. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55698. // V contribution and Sum
  55699. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55700. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55701. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55702. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55703. //add face axis
  55704. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55705. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55706. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55707. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55708. //normalize vector
  55709. PMREMGenerator._vectorTemp.normalize();
  55710. return PMREMGenerator._vectorTemp;
  55711. };
  55712. //--------------------------------------------------------------------------------------
  55713. // Convert 3D vector to cubemap face texel coordinates and face idx
  55714. // note the U and V coords are integer coords and range from 0 to size-1
  55715. // this routine can be used to generate a normalizer cube map
  55716. //
  55717. // returns face IDX and texel coords
  55718. //--------------------------------------------------------------------------------------
  55719. // SL BEGIN
  55720. /*
  55721. Mapping Texture Coordinates to Cube Map Faces
  55722. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55723. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55724. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55725. map arrangement in Pixar's RenderMan package.
  55726. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55727. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55728. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55729. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55730. the major axis direction). The target column in the table below explains how the major axis direction
  55731. maps to the 2D image of a particular cube map target.
  55732. major axis
  55733. direction target sc tc ma
  55734. ---------- --------------------------------- --- --- ---
  55735. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55736. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55737. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55738. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55739. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55740. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55741. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55742. an updated (s,t) is calculated as follows
  55743. s = ( sc/|ma| + 1 ) / 2
  55744. t = ( tc/|ma| + 1 ) / 2
  55745. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55746. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55747. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55748. */
  55749. // Note this method return U and V in range from 0 to size-1
  55750. // SL END
  55751. // Store the information in vector3 for convenience (faceindex, u, v)
  55752. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55753. var maxCoord;
  55754. var faceIdx;
  55755. //absolute value 3
  55756. var absX = Math.abs(x);
  55757. var absY = Math.abs(y);
  55758. var absZ = Math.abs(z);
  55759. if (absX >= absY && absX >= absZ) {
  55760. maxCoord = absX;
  55761. if (x >= 0) {
  55762. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55763. }
  55764. else {
  55765. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55766. }
  55767. }
  55768. else if (absY >= absX && absY >= absZ) {
  55769. maxCoord = absY;
  55770. if (y >= 0) {
  55771. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55772. }
  55773. else {
  55774. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55775. }
  55776. }
  55777. else {
  55778. maxCoord = absZ;
  55779. if (z >= 0) {
  55780. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55781. }
  55782. else {
  55783. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55784. }
  55785. }
  55786. //divide through by max coord so face vector lies on cube face
  55787. var scale = 1 / maxCoord;
  55788. x *= scale;
  55789. y *= scale;
  55790. z *= scale;
  55791. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55792. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55793. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55794. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55795. // Modify original AMD code to return value from 0 to Size - 1
  55796. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55797. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55798. PMREMGenerator._vectorTemp.x = faceIdx;
  55799. PMREMGenerator._vectorTemp.y = u;
  55800. PMREMGenerator._vectorTemp.z = v;
  55801. return PMREMGenerator._vectorTemp;
  55802. };
  55803. //--------------------------------------------------------------------------------------
  55804. //Original code from Ignacio CastaÒo
  55805. // This formula is from Manne ÷hrstrˆm's thesis.
  55806. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55807. // cube face and return the area of the projection of that portion on the
  55808. // surface of the sphere.
  55809. //--------------------------------------------------------------------------------------
  55810. PMREMGenerator.prototype.areaElement = function (x, y) {
  55811. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55812. };
  55813. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55814. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55815. // (+ 0.5f is for texel center addressing)
  55816. u = (2.0 * (u + 0.5) / size) - 1.0;
  55817. v = (2.0 * (v + 0.5) / size) - 1.0;
  55818. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55819. var invResolution = 1.0 / size;
  55820. // U and V are the -1..1 texture coordinate on the current face.
  55821. // Get projected area for this texel
  55822. var x0 = u - invResolution;
  55823. var y0 = v - invResolution;
  55824. var x1 = u + invResolution;
  55825. var y1 = v + invResolution;
  55826. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55827. return solidAngle;
  55828. };
  55829. //--------------------------------------------------------------------------------------
  55830. //The key to the speed of these filtering routines is to quickly define a per-face
  55831. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55832. // Later these pixels are selectively processed based on their dot products to see if
  55833. // they reside within the filtering cone.
  55834. //
  55835. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55836. // of the number of texels needed to be covered in width and height order to filter the
  55837. // region. the bounding box for the center taps face is defined first, and if the
  55838. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55839. // defined next
  55840. //--------------------------------------------------------------------------------------
  55841. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55842. // note that pixels within these regions may be rejected
  55843. // based on the anlge
  55844. var iCubeFace;
  55845. var u;
  55846. var v;
  55847. // bounding box per face to specify region to process
  55848. var filterExtents = [];
  55849. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55850. filterExtents.push(new CMGBoundinBox());
  55851. }
  55852. // min angle a src texel can cover (in degrees)
  55853. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55854. // angle about center tap to define filter cone
  55855. // filter angle is 1/2 the cone angle
  55856. var filterAngle = filterConeAngle / 2.0;
  55857. //ensure filter angle is larger than a texel
  55858. if (filterAngle < srcTexelAngle) {
  55859. filterAngle = srcTexelAngle;
  55860. }
  55861. //ensure filter cone is always smaller than the hemisphere
  55862. if (filterAngle > 90.0) {
  55863. filterAngle = 90.0;
  55864. }
  55865. // the maximum number of texels in 1D the filter cone angle will cover
  55866. // used to determine bounding box size for filter extents
  55867. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55868. // ensure conservative region always covers at least one texel
  55869. if (filterSize < 1) {
  55870. filterSize = 1;
  55871. }
  55872. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55873. // reside within the cone angle
  55874. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55875. // process required faces
  55876. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55877. //iterate over dst cube map face texel
  55878. for (v = 0; v < dstSize; v++) {
  55879. for (u = 0; u < dstSize; u++) {
  55880. //get center tap direction
  55881. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55882. //clear old per-face filter extents
  55883. this.clearFilterExtents(filterExtents);
  55884. //define per-face filter extents
  55885. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55886. //perform filtering of src faces using filter extents
  55887. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55888. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55889. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55890. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55891. }
  55892. }
  55893. }
  55894. };
  55895. //--------------------------------------------------------------------------------------
  55896. //Clear filter extents for the 6 cube map faces
  55897. //--------------------------------------------------------------------------------------
  55898. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55899. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55900. filterExtents[iCubeFaces].clear();
  55901. }
  55902. };
  55903. //--------------------------------------------------------------------------------------
  55904. //Define per-face bounding box filter extents
  55905. //
  55906. // These define conservative texel regions in each of the faces the filter can possibly
  55907. // process. When the pixels in the regions are actually processed, the dot product
  55908. // between the tap vector and the center tap vector is used to determine the weight of
  55909. // the tap and whether or not the tap is within the cone.
  55910. //
  55911. //--------------------------------------------------------------------------------------
  55912. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55913. //neighboring face and bleed over amount, and width of BBOX for
  55914. // left, right, top, and bottom edges of this face
  55915. var bleedOverAmount = [0, 0, 0, 0];
  55916. var bleedOverBBoxMin = [0, 0, 0, 0];
  55917. var bleedOverBBoxMax = [0, 0, 0, 0];
  55918. var neighborFace;
  55919. var neighborEdge;
  55920. var oppositeFaceIdx;
  55921. //get face idx, and u, v info from center tap dir
  55922. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55923. var faceIdx = result.x;
  55924. var u = result.y;
  55925. var v = result.z;
  55926. //define bbox size within face
  55927. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55928. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55929. filterExtents[faceIdx].clampMin(0, 0, 0);
  55930. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55931. //u and v extent in face corresponding to center tap
  55932. var minU = filterExtents[faceIdx].min.x;
  55933. var minV = filterExtents[faceIdx].min.y;
  55934. var maxU = filterExtents[faceIdx].max.x;
  55935. var maxV = filterExtents[faceIdx].max.y;
  55936. //bleed over amounts for face across u=0 edge (left)
  55937. bleedOverAmount[0] = (bboxSize - u);
  55938. bleedOverBBoxMin[0] = minV;
  55939. bleedOverBBoxMax[0] = maxV;
  55940. //bleed over amounts for face across u=1 edge (right)
  55941. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55942. bleedOverBBoxMin[1] = minV;
  55943. bleedOverBBoxMax[1] = maxV;
  55944. //bleed over to face across v=0 edge (up)
  55945. bleedOverAmount[2] = (bboxSize - v);
  55946. bleedOverBBoxMin[2] = minU;
  55947. bleedOverBBoxMax[2] = maxU;
  55948. //bleed over to face across v=1 edge (down)
  55949. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55950. bleedOverBBoxMin[3] = minU;
  55951. bleedOverBBoxMax[3] = maxU;
  55952. //compute bleed over regions in neighboring faces
  55953. for (var i = 0; i < 4; i++) {
  55954. if (bleedOverAmount[i] > 0) {
  55955. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55956. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55957. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55958. // be flipped: the cases are
  55959. // if a left edge mates with a left or bottom edge on the neighbor
  55960. // if a top edge mates with a top or right edge on the neighbor
  55961. // if a right edge mates with a right or top edge on the neighbor
  55962. // if a bottom edge mates with a bottom or left edge on the neighbor
  55963. //Seeing as the edges are enumerated as follows
  55964. // left =0
  55965. // right =1
  55966. // top =2
  55967. // bottom =3
  55968. //
  55969. // so if the edge enums are the same, or the sum of the enums == 3,
  55970. // the bbox needs to be flipped
  55971. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55972. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55973. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55974. }
  55975. //The way the bounding box is extended onto the neighboring face
  55976. // depends on which edge of neighboring face abuts with this one
  55977. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55978. case PMREMGenerator.CP_EDGE_LEFT:
  55979. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55980. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55981. break;
  55982. case PMREMGenerator.CP_EDGE_RIGHT:
  55983. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55984. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55985. break;
  55986. case PMREMGenerator.CP_EDGE_TOP:
  55987. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55988. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55989. break;
  55990. case PMREMGenerator.CP_EDGE_BOTTOM:
  55991. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55992. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55993. break;
  55994. }
  55995. //clamp filter extents in non-center tap faces to remain within surface
  55996. filterExtents[neighborFace].clampMin(0, 0, 0);
  55997. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55998. }
  55999. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  56000. // from the center tap face, then process the opposite face entirely for now.
  56001. //Note that the cases in which this happens, what usually happens is that
  56002. // more than one edge bleeds onto the opposite face, and the bounding box
  56003. // encompasses the entire cube map face.
  56004. if (bleedOverAmount[i] > srcSize) {
  56005. //determine opposite face
  56006. switch (faceIdx) {
  56007. case PMREMGenerator.CP_FACE_X_POS:
  56008. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56009. break;
  56010. case PMREMGenerator.CP_FACE_X_NEG:
  56011. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  56012. break;
  56013. case PMREMGenerator.CP_FACE_Y_POS:
  56014. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56015. break;
  56016. case PMREMGenerator.CP_FACE_Y_NEG:
  56017. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56018. break;
  56019. case PMREMGenerator.CP_FACE_Z_POS:
  56020. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56021. break;
  56022. case PMREMGenerator.CP_FACE_Z_NEG:
  56023. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56024. break;
  56025. default:
  56026. break;
  56027. }
  56028. //just encompass entire face for now
  56029. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  56030. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  56031. }
  56032. }
  56033. };
  56034. //--------------------------------------------------------------------------------------
  56035. //ProcessFilterExtents
  56036. // Process bounding box in each cube face
  56037. //
  56038. //--------------------------------------------------------------------------------------
  56039. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  56040. //accumulators are 64-bit floats in order to have the precision needed
  56041. // over a summation of a large number of pixels
  56042. var dstAccum = [0, 0, 0, 0];
  56043. var weightAccum = 0;
  56044. var k = 0;
  56045. var nSrcChannels = this.numChannels;
  56046. // norm cube map and srcCubeMap have same face width
  56047. var faceWidth = srcSize;
  56048. //amount to add to pointer to move to next scanline in images
  56049. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  56050. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  56051. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  56052. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  56053. // iterate over cubefaces
  56054. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56055. //if bbox is non empty
  56056. if (!filterExtents[iFaceIdx].empty()) {
  56057. var uStart = filterExtents[iFaceIdx].min.x;
  56058. var vStart = filterExtents[iFaceIdx].min.y;
  56059. var uEnd = filterExtents[iFaceIdx].max.x;
  56060. var vEnd = filterExtents[iFaceIdx].max.y;
  56061. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56062. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56063. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56064. for (var v = vStart; v <= vEnd; v++) {
  56065. var normCubeRowWalk = 0;
  56066. var srcCubeRowWalk = 0;
  56067. for (var u = uStart; u <= uEnd; u++) {
  56068. //pointer to direction in cube map associated with texel
  56069. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56070. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56071. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56072. //check dot product to see if texel is within cone
  56073. var tapDotProd = texelVectX * centerTapDir.x +
  56074. texelVectY * centerTapDir.y +
  56075. texelVectZ * centerTapDir.z;
  56076. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56077. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56078. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56079. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56080. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56081. // so just adding one to specularpower do the trick.
  56082. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56083. //iterate over channels
  56084. for (k = 0; k < nSrcChannels; k++) {
  56085. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56086. srcCubeRowWalk++;
  56087. }
  56088. weightAccum += weight; //accumulate weight
  56089. }
  56090. else {
  56091. //step across source pixel
  56092. srcCubeRowWalk += nSrcChannels;
  56093. }
  56094. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56095. }
  56096. startIndexNormCubeMap += normCubePitch;
  56097. startIndexSrcCubeMap += srcCubePitch;
  56098. }
  56099. }
  56100. }
  56101. //divide through by weights if weight is non zero
  56102. if (weightAccum != 0.0) {
  56103. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56104. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56105. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56106. if (this.numChannels > 3) {
  56107. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56108. }
  56109. }
  56110. else {
  56111. // otherwise sample nearest
  56112. // get face idx and u, v texel coordinate in face
  56113. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56114. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56115. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56116. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56117. if (this.numChannels > 3) {
  56118. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56119. }
  56120. }
  56121. return PMREMGenerator._vectorTemp;
  56122. };
  56123. //--------------------------------------------------------------------------------------
  56124. // Fixup cube edges
  56125. //
  56126. // average texels on cube map faces across the edges
  56127. // WARP/BENT Method Only.
  56128. //--------------------------------------------------------------------------------------
  56129. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56130. var k;
  56131. var j;
  56132. var i;
  56133. var iFace;
  56134. var iCorner = 0;
  56135. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56136. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56137. // note that if functionality to filter across the three texels for each corner, then
  56138. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56139. var cornerPtr = [
  56140. [[], [], []],
  56141. [[], [], []],
  56142. [[], [], []],
  56143. [[], [], []],
  56144. [[], [], []],
  56145. [[], [], []],
  56146. [[], [], []],
  56147. [[], [], []]
  56148. ];
  56149. //if there is no fixup, or fixup width = 0, do nothing
  56150. if (cubeMapSize < 1) {
  56151. return;
  56152. }
  56153. //special case 1x1 cubemap, average face colors
  56154. if (cubeMapSize == 1) {
  56155. //iterate over channels
  56156. for (k = 0; k < this.numChannels; k++) {
  56157. var accum = 0.0;
  56158. //iterate over faces to accumulate face colors
  56159. for (iFace = 0; iFace < 6; iFace++) {
  56160. accum += cubeMap[iFace][k];
  56161. }
  56162. //compute average over 6 face colors
  56163. accum /= 6.0;
  56164. //iterate over faces to distribute face colors
  56165. for (iFace = 0; iFace < 6; iFace++) {
  56166. cubeMap[iFace][k] = accum;
  56167. }
  56168. }
  56169. return;
  56170. }
  56171. //iterate over faces to collect list of corner texel pointers
  56172. for (iFace = 0; iFace < 6; iFace++) {
  56173. //the 4 corner pointers for this face
  56174. faceCornerStartIndicies[0] = [iFace, 0];
  56175. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56176. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56177. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56178. //iterate over face corners to collect cube corner pointers
  56179. for (iCorner = 0; iCorner < 4; iCorner++) {
  56180. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56181. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56182. cornerNumPtrs[corner]++;
  56183. }
  56184. }
  56185. //iterate over corners to average across corner tap values
  56186. for (iCorner = 0; iCorner < 8; iCorner++) {
  56187. for (k = 0; k < this.numChannels; k++) {
  56188. var cornerTapAccum = 0.0;
  56189. //iterate over corner texels and average results
  56190. for (i = 0; i < 3; i++) {
  56191. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56192. }
  56193. //divide by 3 to compute average of corner tap values
  56194. cornerTapAccum *= (1.0 / 3.0);
  56195. //iterate over corner texels and average results
  56196. for (i = 0; i < 3; i++) {
  56197. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56198. }
  56199. }
  56200. }
  56201. //iterate over the twelve edges of the cube to average across edges
  56202. for (i = 0; i < 12; i++) {
  56203. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56204. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56205. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56206. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56207. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56208. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56209. var edgeWalk = 0;
  56210. var neighborEdgeWalk = 0;
  56211. //Determine walking pointers based on edge type
  56212. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56213. switch (edge) {
  56214. case PMREMGenerator.CP_EDGE_LEFT:
  56215. // no change to faceEdgeStartPtr
  56216. edgeWalk = this.numChannels * cubeMapSize;
  56217. break;
  56218. case PMREMGenerator.CP_EDGE_RIGHT:
  56219. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56220. edgeWalk = this.numChannels * cubeMapSize;
  56221. break;
  56222. case PMREMGenerator.CP_EDGE_TOP:
  56223. // no change to faceEdgeStartPtr
  56224. edgeWalk = this.numChannels;
  56225. break;
  56226. case PMREMGenerator.CP_EDGE_BOTTOM:
  56227. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56228. edgeWalk = this.numChannels;
  56229. break;
  56230. }
  56231. //For certain types of edge abutments, the neighbor edge walk needs to
  56232. // be flipped: the cases are
  56233. // if a left edge mates with a left or bottom edge on the neighbor
  56234. // if a top edge mates with a top or right edge on the neighbor
  56235. // if a right edge mates with a right or top edge on the neighbor
  56236. // if a bottom edge mates with a bottom or left edge on the neighbor
  56237. //Seeing as the edges are enumerated as follows
  56238. // left =0
  56239. // right =1
  56240. // top =2
  56241. // bottom =3
  56242. //
  56243. //If the edge enums are the same, or the sum of the enums == 3,
  56244. // the neighbor edge walk needs to be flipped
  56245. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56246. switch (neighborEdge) {
  56247. case PMREMGenerator.CP_EDGE_LEFT:
  56248. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56249. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56250. break;
  56251. case PMREMGenerator.CP_EDGE_RIGHT:
  56252. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56253. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56254. break;
  56255. case PMREMGenerator.CP_EDGE_TOP:
  56256. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56257. neighborEdgeWalk = -this.numChannels;
  56258. break;
  56259. case PMREMGenerator.CP_EDGE_BOTTOM:
  56260. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56261. neighborEdgeWalk = -this.numChannels;
  56262. break;
  56263. }
  56264. }
  56265. else {
  56266. //swapped direction neighbor edge walk
  56267. switch (neighborEdge) {
  56268. case PMREMGenerator.CP_EDGE_LEFT:
  56269. //no change to neighborEdgeStartPtr for this case since it points
  56270. // to the upper left corner already
  56271. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56272. break;
  56273. case PMREMGenerator.CP_EDGE_RIGHT:
  56274. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56275. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56276. break;
  56277. case PMREMGenerator.CP_EDGE_TOP:
  56278. //no change to neighborEdgeStartPtr for this case since it points
  56279. // to the upper left corner already
  56280. neighborEdgeWalk = this.numChannels;
  56281. break;
  56282. case PMREMGenerator.CP_EDGE_BOTTOM:
  56283. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56284. neighborEdgeWalk = this.numChannels;
  56285. break;
  56286. }
  56287. }
  56288. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56289. //nearby neighborhood
  56290. //step ahead one texel on edge
  56291. edgeStartIndex += edgeWalk;
  56292. neighborEdgeStartIndex += neighborEdgeWalk;
  56293. // note that this loop does not process the corner texels, since they have already been
  56294. // averaged across faces across earlier
  56295. for (j = 1; j < (cubeMapSize - 1); j++) {
  56296. //for each set of taps along edge, average them
  56297. // and rewrite the results into the edges
  56298. for (k = 0; k < this.numChannels; k++) {
  56299. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56300. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56301. //compute average of tap intensity values
  56302. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56303. //propagate average of taps to edge taps
  56304. cubeMap[face][edgeStartIndex + k] = avgTap;
  56305. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56306. }
  56307. edgeStartIndex += edgeWalk;
  56308. neighborEdgeStartIndex += neighborEdgeWalk;
  56309. }
  56310. }
  56311. };
  56312. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56313. PMREMGenerator.CP_UDIR = 0;
  56314. PMREMGenerator.CP_VDIR = 1;
  56315. PMREMGenerator.CP_FACEAXIS = 2;
  56316. //used to index cube faces
  56317. PMREMGenerator.CP_FACE_X_POS = 0;
  56318. PMREMGenerator.CP_FACE_X_NEG = 1;
  56319. PMREMGenerator.CP_FACE_Y_POS = 2;
  56320. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56321. PMREMGenerator.CP_FACE_Z_POS = 4;
  56322. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56323. //used to index image edges
  56324. // NOTE.. the actual number corresponding to the edge is important
  56325. // do not change these, or the code will break
  56326. //
  56327. // CP_EDGE_LEFT is u = 0
  56328. // CP_EDGE_RIGHT is u = width-1
  56329. // CP_EDGE_TOP is v = 0
  56330. // CP_EDGE_BOTTOM is v = height-1
  56331. PMREMGenerator.CP_EDGE_LEFT = 0;
  56332. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56333. PMREMGenerator.CP_EDGE_TOP = 2;
  56334. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56335. //corners of CUBE map (P or N specifys if it corresponds to the
  56336. // positive or negative direction each of X, Y, and Z
  56337. PMREMGenerator.CP_CORNER_NNN = 0;
  56338. PMREMGenerator.CP_CORNER_NNP = 1;
  56339. PMREMGenerator.CP_CORNER_NPN = 2;
  56340. PMREMGenerator.CP_CORNER_NPP = 3;
  56341. PMREMGenerator.CP_CORNER_PNN = 4;
  56342. PMREMGenerator.CP_CORNER_PNP = 5;
  56343. PMREMGenerator.CP_CORNER_PPN = 6;
  56344. PMREMGenerator.CP_CORNER_PPP = 7;
  56345. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56346. //3x2 matrices that map cube map indexing vectors in 3d
  56347. // (after face selection and divide through by the
  56348. // _ABSOLUTE VALUE_ of the max coord)
  56349. // into NVC space
  56350. //Note this currently assumes the D3D cube face ordering and orientation
  56351. PMREMGenerator._sgFace2DMapping = [
  56352. //XPOS face
  56353. [[0, 0, -1],
  56354. [0, -1, 0],
  56355. [1, 0, 0]],
  56356. //XNEG face
  56357. [[0, 0, 1],
  56358. [0, -1, 0],
  56359. [-1, 0, 0]],
  56360. //YPOS face
  56361. [[1, 0, 0],
  56362. [0, 0, 1],
  56363. [0, 1, 0]],
  56364. //YNEG face
  56365. [[1, 0, 0],
  56366. [0, 0, -1],
  56367. [0, -1, 0]],
  56368. //ZPOS face
  56369. [[1, 0, 0],
  56370. [0, -1, 0],
  56371. [0, 0, 1]],
  56372. //ZNEG face
  56373. [[-1, 0, 0],
  56374. [0, -1, 0],
  56375. [0, 0, -1]],
  56376. ];
  56377. //------------------------------------------------------------------------------
  56378. // D3D cube map face specification
  56379. // mapping from 3D x,y,z cube map lookup coordinates
  56380. // to 2D within face u,v coordinates
  56381. //
  56382. // --------------------> U direction
  56383. // | (within-face texture space)
  56384. // | _____
  56385. // | | |
  56386. // | | +Y |
  56387. // | _____|_____|_____ _____
  56388. // | | | | | |
  56389. // | | -X | +Z | +X | -Z |
  56390. // | |_____|_____|_____|_____|
  56391. // | | |
  56392. // | | -Y |
  56393. // | |_____|
  56394. // |
  56395. // v V direction
  56396. // (within-face texture space)
  56397. //------------------------------------------------------------------------------
  56398. //Information about neighbors and how texture coorrdinates change across faces
  56399. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56400. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56401. //Note this currently assumes the D3D cube face ordering and orientation
  56402. PMREMGenerator._sgCubeNgh = [
  56403. //XPOS face
  56404. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56405. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56406. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56407. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56408. //XNEG face
  56409. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56410. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56411. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56412. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56413. //YPOS face
  56414. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56415. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56416. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56417. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56418. //YNEG face
  56419. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56420. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56421. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56422. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56423. //ZPOS face
  56424. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56425. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56426. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56427. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56428. //ZNEG face
  56429. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56430. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56431. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56432. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56433. ];
  56434. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56435. // this table is used to average over the edges.
  56436. PMREMGenerator._sgCubeEdgeList = [
  56437. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56438. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56439. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56440. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56441. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56442. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56443. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56444. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56445. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56446. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56447. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56448. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56449. ];
  56450. //Information about which of the 8 cube corners are correspond to the
  56451. // the 4 corners in each cube face
  56452. // the order is upper left, upper right, lower left, lower right
  56453. PMREMGenerator._sgCubeCornerList = [
  56454. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56455. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56456. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56457. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56458. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56459. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56460. ];
  56461. return PMREMGenerator;
  56462. })();
  56463. Internals.PMREMGenerator = PMREMGenerator;
  56464. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56465. })(BABYLON || (BABYLON = {}));
  56466. var BABYLON;
  56467. (function (BABYLON) {
  56468. /**
  56469. * This represents a texture coming from an HDR input.
  56470. *
  56471. * The only supported format is currently panorama picture stored in RGBE format.
  56472. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56473. */
  56474. var HDRCubeTexture = (function (_super) {
  56475. __extends(HDRCubeTexture, _super);
  56476. /**
  56477. * Instantiates an HDRTexture from the following parameters.
  56478. *
  56479. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56480. * @param scene The scene the texture will be used in
  56481. * @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.
  56482. * @param noMipmap Forces to not generate the mipmap if true
  56483. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56484. * @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)
  56485. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56486. */
  56487. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  56488. if (noMipmap === void 0) { noMipmap = false; }
  56489. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56490. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56491. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56492. _super.call(this, scene);
  56493. this._useInGammaSpace = false;
  56494. this._generateHarmonics = true;
  56495. this._isBABYLONPreprocessed = false;
  56496. /**
  56497. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56498. */
  56499. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56500. /**
  56501. * The spherical polynomial data extracted from the texture.
  56502. */
  56503. this.sphericalPolynomial = null;
  56504. /**
  56505. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56506. * This is usefull at run time to apply the good shader.
  56507. */
  56508. this.isPMREM = false;
  56509. if (!url) {
  56510. return;
  56511. }
  56512. this.name = url;
  56513. this.url = url;
  56514. this.hasAlpha = false;
  56515. this.isCube = true;
  56516. this._textureMatrix = BABYLON.Matrix.Identity();
  56517. if (size) {
  56518. this._isBABYLONPreprocessed = false;
  56519. this._noMipmap = noMipmap;
  56520. this._size = size;
  56521. this._useInGammaSpace = useInGammaSpace;
  56522. this._usePMREMGenerator = usePMREMGenerator &&
  56523. scene.getEngine().getCaps().textureLOD &&
  56524. this.getScene().getEngine().getCaps().textureFloat &&
  56525. !this._useInGammaSpace;
  56526. }
  56527. else {
  56528. this._isBABYLONPreprocessed = true;
  56529. this._noMipmap = false;
  56530. this._useInGammaSpace = false;
  56531. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56532. this.getScene().getEngine().getCaps().textureFloat &&
  56533. !this._useInGammaSpace;
  56534. }
  56535. this.isPMREM = this._usePMREMGenerator;
  56536. this._texture = this._getFromCache(url, this._noMipmap);
  56537. if (!this._texture) {
  56538. if (!scene.useDelayedTextureLoading) {
  56539. this.loadTexture();
  56540. }
  56541. else {
  56542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56543. }
  56544. }
  56545. }
  56546. /**
  56547. * Occurs when the file is a preprocessed .babylon.hdr file.
  56548. */
  56549. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56550. var _this = this;
  56551. var mipLevels = 0;
  56552. var floatArrayView = null;
  56553. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56554. var mips = [];
  56555. var startIndex = 30;
  56556. for (var level = 0; level < mipLevels; level++) {
  56557. mips.push([]);
  56558. // Fill each pixel of the mip level.
  56559. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56560. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56561. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56562. mips[level].push(faceData);
  56563. startIndex += faceSize;
  56564. }
  56565. }
  56566. return mips;
  56567. } : null;
  56568. var callback = function (buffer) {
  56569. // Create Native Array Views
  56570. var intArrayView = new Int32Array(buffer);
  56571. floatArrayView = new Float32Array(buffer);
  56572. // Fill header.
  56573. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56574. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56575. // Update Texture Information.
  56576. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56577. // Fill polynomial information.
  56578. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56579. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56580. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56581. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56582. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56583. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56584. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56585. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56586. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56587. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56588. // Fill pixel data.
  56589. mipLevels = intArrayView[29]; // Number of mip levels.
  56590. var startIndex = 30;
  56591. var data = [];
  56592. var faceSize = Math.pow(_this._size, 2) * 3;
  56593. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56594. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56595. startIndex += faceSize;
  56596. }
  56597. var results = [];
  56598. var byteArray = null;
  56599. // Push each faces.
  56600. for (var k = 0; k < 6; k++) {
  56601. var dataFace = null;
  56602. // If special cases.
  56603. if (!mipmapGenerator) {
  56604. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56605. dataFace = data[j];
  56606. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56607. // 3 channels of 1 bytes per pixel in bytes.
  56608. var byteBuffer = new ArrayBuffer(faceSize);
  56609. byteArray = new Uint8Array(byteBuffer);
  56610. }
  56611. for (var i = 0; i < _this._size * _this._size; i++) {
  56612. // Put in gamma space if requested.
  56613. if (_this._useInGammaSpace) {
  56614. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56615. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56616. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56617. }
  56618. // Convert to int texture for fallback.
  56619. if (byteArray) {
  56620. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56621. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56622. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56623. // May use luminance instead if the result is not accurate.
  56624. var max = Math.max(Math.max(r, g), b);
  56625. if (max > 255) {
  56626. var scale = 255 / max;
  56627. r *= scale;
  56628. g *= scale;
  56629. b *= scale;
  56630. }
  56631. byteArray[(i * 3) + 0] = r;
  56632. byteArray[(i * 3) + 1] = g;
  56633. byteArray[(i * 3) + 2] = b;
  56634. }
  56635. }
  56636. }
  56637. else {
  56638. dataFace = data[k];
  56639. }
  56640. // Fill the array accordingly.
  56641. if (byteArray) {
  56642. results.push(byteArray);
  56643. }
  56644. else {
  56645. results.push(dataFace);
  56646. }
  56647. }
  56648. return results;
  56649. };
  56650. 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);
  56651. };
  56652. /**
  56653. * Occurs when the file is raw .hdr file.
  56654. */
  56655. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56656. var _this = this;
  56657. var callback = function (buffer) {
  56658. // Extract the raw linear data.
  56659. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56660. // Generate harmonics if needed.
  56661. if (_this._generateHarmonics) {
  56662. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56663. }
  56664. var results = [];
  56665. var byteArray = null;
  56666. // Push each faces.
  56667. for (var j = 0; j < 6; j++) {
  56668. // Create uintarray fallback.
  56669. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56670. // 3 channels of 1 bytes per pixel in bytes.
  56671. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56672. byteArray = new Uint8Array(byteBuffer);
  56673. }
  56674. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56675. // If special cases.
  56676. if (_this._useInGammaSpace || byteArray) {
  56677. for (var i = 0; i < _this._size * _this._size; i++) {
  56678. // Put in gamma space if requested.
  56679. if (_this._useInGammaSpace) {
  56680. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56681. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56682. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56683. }
  56684. // Convert to int texture for fallback.
  56685. if (byteArray) {
  56686. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56687. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56688. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56689. // May use luminance instead if the result is not accurate.
  56690. var max = Math.max(Math.max(r, g), b);
  56691. if (max > 255) {
  56692. var scale = 255 / max;
  56693. r *= scale;
  56694. g *= scale;
  56695. b *= scale;
  56696. }
  56697. byteArray[(i * 3) + 0] = r;
  56698. byteArray[(i * 3) + 1] = g;
  56699. byteArray[(i * 3) + 2] = b;
  56700. }
  56701. }
  56702. }
  56703. if (byteArray) {
  56704. results.push(byteArray);
  56705. }
  56706. else {
  56707. results.push(dataFace);
  56708. }
  56709. }
  56710. return results;
  56711. };
  56712. var mipmapGenerator = null;
  56713. if (!this._noMipmap &&
  56714. this._usePMREMGenerator) {
  56715. mipmapGenerator = function (data) {
  56716. // Custom setup of the generator matching with the PBR shader values.
  56717. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56718. return generator.filterCubeMap();
  56719. };
  56720. }
  56721. 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);
  56722. };
  56723. /**
  56724. * Starts the loading process of the texture.
  56725. */
  56726. HDRCubeTexture.prototype.loadTexture = function () {
  56727. if (this._isBABYLONPreprocessed) {
  56728. this.loadBabylonTexture();
  56729. }
  56730. else {
  56731. this.loadHDRTexture();
  56732. }
  56733. };
  56734. HDRCubeTexture.prototype.clone = function () {
  56735. var size = this._isBABYLONPreprocessed ? null : this._size;
  56736. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56737. // Base texture
  56738. newTexture.level = this.level;
  56739. newTexture.wrapU = this.wrapU;
  56740. newTexture.wrapV = this.wrapV;
  56741. newTexture.coordinatesIndex = this.coordinatesIndex;
  56742. newTexture.coordinatesMode = this.coordinatesMode;
  56743. return newTexture;
  56744. };
  56745. // Methods
  56746. HDRCubeTexture.prototype.delayLoad = function () {
  56747. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56748. return;
  56749. }
  56750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56751. this._texture = this._getFromCache(this.url, this._noMipmap);
  56752. if (!this._texture) {
  56753. this.loadTexture();
  56754. }
  56755. };
  56756. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56757. return this._textureMatrix;
  56758. };
  56759. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56760. var texture = null;
  56761. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56762. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56763. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  56764. texture.name = parsedTexture.name;
  56765. texture.hasAlpha = parsedTexture.hasAlpha;
  56766. texture.level = parsedTexture.level;
  56767. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56768. }
  56769. return texture;
  56770. };
  56771. HDRCubeTexture.prototype.serialize = function () {
  56772. if (!this.name) {
  56773. return null;
  56774. }
  56775. var serializationObject = {};
  56776. serializationObject.name = this.name;
  56777. serializationObject.hasAlpha = this.hasAlpha;
  56778. serializationObject.isCube = true;
  56779. serializationObject.level = this.level;
  56780. serializationObject.size = this._size;
  56781. serializationObject.coordinatesMode = this.coordinatesMode;
  56782. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56783. serializationObject.generateHarmonics = this._generateHarmonics;
  56784. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56785. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56786. return serializationObject;
  56787. };
  56788. /**
  56789. * Saves as a file the data contained in the texture in a binary format.
  56790. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56791. * as the spherical used in the lighting.
  56792. * @param url The HDR file url.
  56793. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56794. * @param onError Method called if any error happens during download.
  56795. * @return The packed binary data.
  56796. */
  56797. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56798. if (onError === void 0) { onError = null; }
  56799. var callback = function (buffer) {
  56800. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56801. // Returns a URL you can use as a href.
  56802. var objUrl = window.URL.createObjectURL(data);
  56803. // Simulates a link to it and click to dowload.
  56804. var a = document.createElement("a");
  56805. document.body.appendChild(a);
  56806. a.style.display = "none";
  56807. a.href = objUrl;
  56808. a.download = "envmap.babylon.hdr";
  56809. a.click();
  56810. };
  56811. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56812. };
  56813. /**
  56814. * Serializes the data contained in the texture in a binary format.
  56815. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56816. * as the spherical used in the lighting.
  56817. * @param url The HDR file url.
  56818. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56819. * @param onError Method called if any error happens during download.
  56820. * @return The packed binary data.
  56821. */
  56822. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56823. if (onError === void 0) { onError = null; }
  56824. // Needs the url tho create the texture.
  56825. if (!url) {
  56826. return null;
  56827. }
  56828. // Check Power of two size.
  56829. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56830. return null;
  56831. }
  56832. var getDataCallback = function (dataBuffer) {
  56833. // Extract the raw linear data.
  56834. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56835. // Generate harmonics if needed.
  56836. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56837. // Generate seamless faces
  56838. var mipGeneratorArray = [];
  56839. // Data are known to be in +X +Y +Z -X -Y -Z
  56840. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56841. mipGeneratorArray.push(cubeData.right); // +X
  56842. mipGeneratorArray.push(cubeData.left); // -X
  56843. mipGeneratorArray.push(cubeData.up); // +Y
  56844. mipGeneratorArray.push(cubeData.down); // -Y
  56845. mipGeneratorArray.push(cubeData.front); // +Z
  56846. mipGeneratorArray.push(cubeData.back); // -Z
  56847. // Custom setup of the generator matching with the PBR shader values.
  56848. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56849. var mippedData = generator.filterCubeMap();
  56850. // Compute required byte length.
  56851. var byteLength = 1 * 4; // Raw Data Version int32.
  56852. byteLength += 4; // CubeMap max mip face size int32.
  56853. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56854. // Add data size.
  56855. byteLength += 4; // Number of mip levels int32.
  56856. for (var level = 0; level < mippedData.length; level++) {
  56857. var mipSize = size >> level;
  56858. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56859. }
  56860. // Prepare binary structure.
  56861. var buffer = new ArrayBuffer(byteLength);
  56862. var intArrayView = new Int32Array(buffer);
  56863. var floatArrayView = new Float32Array(buffer);
  56864. // Fill header.
  56865. intArrayView[0] = 1; // Version 1.
  56866. intArrayView[1] = size; // CubeMap max mip face size.
  56867. // Fill polynomial information.
  56868. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56869. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56870. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56871. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56872. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56873. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56874. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56875. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56876. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56877. // Fill pixel data.
  56878. intArrayView[29] = mippedData.length; // Number of mip levels.
  56879. var startIndex = 30;
  56880. for (var level = 0; level < mippedData.length; level++) {
  56881. // Fill each pixel of the mip level.
  56882. var faceSize = Math.pow(size >> level, 2) * 3;
  56883. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56884. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56885. startIndex += faceSize;
  56886. }
  56887. }
  56888. // Callback.
  56889. callback(buffer);
  56890. };
  56891. // Download and process.
  56892. BABYLON.Tools.LoadFile(url, function (data) {
  56893. getDataCallback(data);
  56894. }, null, null, true, onError);
  56895. };
  56896. HDRCubeTexture._facesMapping = [
  56897. "right",
  56898. "up",
  56899. "front",
  56900. "left",
  56901. "down",
  56902. "back"
  56903. ];
  56904. return HDRCubeTexture;
  56905. })(BABYLON.BaseTexture);
  56906. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56907. })(BABYLON || (BABYLON = {}));
  56908. var BABYLON;
  56909. (function (BABYLON) {
  56910. var Debug;
  56911. (function (Debug) {
  56912. /**
  56913. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56914. */
  56915. var SkeletonViewer = (function () {
  56916. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56917. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56918. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56919. this.skeleton = skeleton;
  56920. this.mesh = mesh;
  56921. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56922. this.renderingGroupId = renderingGroupId;
  56923. this.color = BABYLON.Color3.White();
  56924. this._debugLines = [];
  56925. this._isEnabled = false;
  56926. this._scene = scene;
  56927. this.update();
  56928. this._renderFunction = this.update.bind(this);
  56929. }
  56930. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56931. get: function () {
  56932. return this._isEnabled;
  56933. },
  56934. set: function (value) {
  56935. if (this._isEnabled === value) {
  56936. return;
  56937. }
  56938. this._isEnabled = value;
  56939. if (value) {
  56940. this._scene.registerBeforeRender(this._renderFunction);
  56941. }
  56942. else {
  56943. this._scene.unregisterBeforeRender(this._renderFunction);
  56944. }
  56945. },
  56946. enumerable: true,
  56947. configurable: true
  56948. });
  56949. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56950. if (x === void 0) { x = 0; }
  56951. if (y === void 0) { y = 0; }
  56952. if (z === void 0) { z = 0; }
  56953. var tmat = BABYLON.Tmp.Matrix[0];
  56954. var parentBone = bone.getParent();
  56955. tmat.copyFrom(bone.getLocalMatrix());
  56956. if (x !== 0 || y !== 0 || z !== 0) {
  56957. var tmat2 = BABYLON.Tmp.Matrix[1];
  56958. BABYLON.Matrix.IdentityToRef(tmat2);
  56959. tmat2.m[12] = x;
  56960. tmat2.m[13] = y;
  56961. tmat2.m[14] = z;
  56962. tmat2.multiplyToRef(tmat, tmat);
  56963. }
  56964. if (parentBone) {
  56965. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56966. }
  56967. tmat.multiplyToRef(meshMat, tmat);
  56968. position.x = tmat.m[12];
  56969. position.y = tmat.m[13];
  56970. position.z = tmat.m[14];
  56971. };
  56972. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56973. var len = bones.length;
  56974. for (var i = 0; i < len; i++) {
  56975. var bone = bones[i];
  56976. var points = this._debugLines[i];
  56977. if (!points) {
  56978. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56979. this._debugLines[i] = points;
  56980. }
  56981. this._getBonePosition(points[0], bone, meshMat);
  56982. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56983. }
  56984. };
  56985. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56986. var len = bones.length;
  56987. var boneNum = 0;
  56988. for (var i = len - 1; i >= 0; i--) {
  56989. var childBone = bones[i];
  56990. var parentBone = childBone.getParent();
  56991. if (!parentBone) {
  56992. continue;
  56993. }
  56994. var points = this._debugLines[boneNum];
  56995. if (!points) {
  56996. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56997. this._debugLines[boneNum] = points;
  56998. }
  56999. this._getBonePosition(points[0], childBone, meshMat);
  57000. this._getBonePosition(points[1], parentBone, meshMat);
  57001. boneNum++;
  57002. }
  57003. };
  57004. SkeletonViewer.prototype.update = function () {
  57005. if (this.autoUpdateBonesMatrices) {
  57006. this._updateBoneMatrix(this.skeleton.bones[0]);
  57007. }
  57008. if (this.skeleton.bones[0].length === undefined) {
  57009. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57010. }
  57011. else {
  57012. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57013. }
  57014. if (!this._debugMesh) {
  57015. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  57016. this._debugMesh.renderingGroupId = this.renderingGroupId;
  57017. }
  57018. else {
  57019. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  57020. }
  57021. this._debugMesh.color = this.color;
  57022. };
  57023. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  57024. if (bone.getParent()) {
  57025. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  57026. }
  57027. var children = bone.children;
  57028. var len = children.length;
  57029. for (var i = 0; i < len; i++) {
  57030. this._updateBoneMatrix(children[i]);
  57031. }
  57032. };
  57033. SkeletonViewer.prototype.dispose = function () {
  57034. if (this._debugMesh) {
  57035. this.isEnabled = false;
  57036. this._debugMesh.dispose();
  57037. this._debugMesh = null;
  57038. }
  57039. };
  57040. return SkeletonViewer;
  57041. })();
  57042. Debug.SkeletonViewer = SkeletonViewer;
  57043. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57044. })(BABYLON || (BABYLON = {}));
  57045. var BABYLON;
  57046. (function (BABYLON) {
  57047. /**
  57048. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57049. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57050. * 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;
  57051. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57052. */
  57053. var ColorCurves = (function () {
  57054. function ColorCurves() {
  57055. this._dirty = true;
  57056. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57057. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57058. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57059. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57060. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57061. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57062. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57063. this._globalHue = 30;
  57064. this._globalDensity = 0;
  57065. this._globalSaturation = 0;
  57066. this._globalExposure = 0;
  57067. this._highlightsHue = 30;
  57068. this._highlightsDensity = 0;
  57069. this._highlightsSaturation = 0;
  57070. this._highlightsExposure = 0;
  57071. this._midtonesHue = 30;
  57072. this._midtonesDensity = 0;
  57073. this._midtonesSaturation = 0;
  57074. this._midtonesExposure = 0;
  57075. this._shadowsHue = 30;
  57076. this._shadowsDensity = 0;
  57077. this._shadowsSaturation = 0;
  57078. this._shadowsExposure = 0;
  57079. }
  57080. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57081. /**
  57082. * Gets the global Hue value.
  57083. * 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).
  57084. */
  57085. get: function () {
  57086. return this._globalHue;
  57087. },
  57088. /**
  57089. * Sets the global Hue value.
  57090. * 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).
  57091. */
  57092. set: function (value) {
  57093. this._globalHue = value;
  57094. this._dirty = true;
  57095. },
  57096. enumerable: true,
  57097. configurable: true
  57098. });
  57099. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57100. /**
  57101. * Gets the global Density value.
  57102. * 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.
  57103. * Values less than zero provide a filter of opposite hue.
  57104. */
  57105. get: function () {
  57106. return this._globalDensity;
  57107. },
  57108. /**
  57109. * Sets the global Density value.
  57110. * 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.
  57111. * Values less than zero provide a filter of opposite hue.
  57112. */
  57113. set: function (value) {
  57114. this._globalDensity = value;
  57115. this._dirty = true;
  57116. },
  57117. enumerable: true,
  57118. configurable: true
  57119. });
  57120. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57121. /**
  57122. * Gets the global Saturation value.
  57123. * 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.
  57124. */
  57125. get: function () {
  57126. return this._globalSaturation;
  57127. },
  57128. /**
  57129. * Sets the global Saturation value.
  57130. * 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.
  57131. */
  57132. set: function (value) {
  57133. this._globalSaturation = value;
  57134. this._dirty = true;
  57135. },
  57136. enumerable: true,
  57137. configurable: true
  57138. });
  57139. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57140. /**
  57141. * Gets the highlights Hue value.
  57142. * 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).
  57143. */
  57144. get: function () {
  57145. return this._highlightsHue;
  57146. },
  57147. /**
  57148. * Sets the highlights Hue value.
  57149. * 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).
  57150. */
  57151. set: function (value) {
  57152. this._highlightsHue = value;
  57153. this._dirty = true;
  57154. },
  57155. enumerable: true,
  57156. configurable: true
  57157. });
  57158. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57159. /**
  57160. * Gets the highlights Density value.
  57161. * 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.
  57162. * Values less than zero provide a filter of opposite hue.
  57163. */
  57164. get: function () {
  57165. return this._highlightsDensity;
  57166. },
  57167. /**
  57168. * Sets the highlights Density value.
  57169. * 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.
  57170. * Values less than zero provide a filter of opposite hue.
  57171. */
  57172. set: function (value) {
  57173. this._highlightsDensity = value;
  57174. this._dirty = true;
  57175. },
  57176. enumerable: true,
  57177. configurable: true
  57178. });
  57179. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57180. /**
  57181. * Gets the highlights Saturation value.
  57182. * 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.
  57183. */
  57184. get: function () {
  57185. return this._highlightsSaturation;
  57186. },
  57187. /**
  57188. * Sets the highlights Saturation value.
  57189. * 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.
  57190. */
  57191. set: function (value) {
  57192. this._highlightsSaturation = value;
  57193. this._dirty = true;
  57194. },
  57195. enumerable: true,
  57196. configurable: true
  57197. });
  57198. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57199. /**
  57200. * Gets the highlights Exposure value.
  57201. * 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.
  57202. */
  57203. get: function () {
  57204. return this._highlightsExposure;
  57205. },
  57206. /**
  57207. * Sets the highlights Exposure value.
  57208. * 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.
  57209. */
  57210. set: function (value) {
  57211. this._highlightsExposure = value;
  57212. this._dirty = true;
  57213. },
  57214. enumerable: true,
  57215. configurable: true
  57216. });
  57217. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57218. /**
  57219. * Gets the midtones Hue value.
  57220. * 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).
  57221. */
  57222. get: function () {
  57223. return this._midtonesHue;
  57224. },
  57225. /**
  57226. * Sets the midtones Hue value.
  57227. * 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).
  57228. */
  57229. set: function (value) {
  57230. this._midtonesHue = value;
  57231. this._dirty = true;
  57232. },
  57233. enumerable: true,
  57234. configurable: true
  57235. });
  57236. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57237. /**
  57238. * Gets the midtones Density value.
  57239. * 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.
  57240. * Values less than zero provide a filter of opposite hue.
  57241. */
  57242. get: function () {
  57243. return this._midtonesDensity;
  57244. },
  57245. /**
  57246. * Sets the midtones Density value.
  57247. * 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.
  57248. * Values less than zero provide a filter of opposite hue.
  57249. */
  57250. set: function (value) {
  57251. this._midtonesDensity = value;
  57252. this._dirty = true;
  57253. },
  57254. enumerable: true,
  57255. configurable: true
  57256. });
  57257. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57258. /**
  57259. * Gets the midtones Saturation value.
  57260. * 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.
  57261. */
  57262. get: function () {
  57263. return this._midtonesSaturation;
  57264. },
  57265. /**
  57266. * Sets the midtones Saturation value.
  57267. * 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.
  57268. */
  57269. set: function (value) {
  57270. this._midtonesSaturation = value;
  57271. this._dirty = true;
  57272. },
  57273. enumerable: true,
  57274. configurable: true
  57275. });
  57276. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57277. /**
  57278. * Gets the midtones Exposure value.
  57279. * 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.
  57280. */
  57281. get: function () {
  57282. return this._midtonesExposure;
  57283. },
  57284. /**
  57285. * Sets the midtones Exposure value.
  57286. * 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.
  57287. */
  57288. set: function (value) {
  57289. this._midtonesExposure = value;
  57290. this._dirty = true;
  57291. },
  57292. enumerable: true,
  57293. configurable: true
  57294. });
  57295. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57296. /**
  57297. * Gets the shadows Hue value.
  57298. * 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).
  57299. */
  57300. get: function () {
  57301. return this._shadowsHue;
  57302. },
  57303. /**
  57304. * Sets the shadows Hue value.
  57305. * 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).
  57306. */
  57307. set: function (value) {
  57308. this._shadowsHue = value;
  57309. this._dirty = true;
  57310. },
  57311. enumerable: true,
  57312. configurable: true
  57313. });
  57314. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57315. /**
  57316. * Gets the shadows Density value.
  57317. * 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.
  57318. * Values less than zero provide a filter of opposite hue.
  57319. */
  57320. get: function () {
  57321. return this._shadowsDensity;
  57322. },
  57323. /**
  57324. * Sets the shadows Density value.
  57325. * 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.
  57326. * Values less than zero provide a filter of opposite hue.
  57327. */
  57328. set: function (value) {
  57329. this._shadowsDensity = value;
  57330. this._dirty = true;
  57331. },
  57332. enumerable: true,
  57333. configurable: true
  57334. });
  57335. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57336. /**
  57337. * Gets the shadows Saturation value.
  57338. * 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.
  57339. */
  57340. get: function () {
  57341. return this._shadowsSaturation;
  57342. },
  57343. /**
  57344. * Sets the shadows Saturation value.
  57345. * 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.
  57346. */
  57347. set: function (value) {
  57348. this._shadowsSaturation = value;
  57349. this._dirty = true;
  57350. },
  57351. enumerable: true,
  57352. configurable: true
  57353. });
  57354. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57355. /**
  57356. * Gets the shadows Exposure value.
  57357. * 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.
  57358. */
  57359. get: function () {
  57360. return this._shadowsExposure;
  57361. },
  57362. /**
  57363. * Sets the shadows Exposure value.
  57364. * 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.
  57365. */
  57366. set: function (value) {
  57367. this._shadowsExposure = value;
  57368. this._dirty = true;
  57369. },
  57370. enumerable: true,
  57371. configurable: true
  57372. });
  57373. /**
  57374. * Binds the color curves to the shader.
  57375. * @param colorCurves The color curve to bind
  57376. * @param effect The effect to bind to
  57377. */
  57378. ColorCurves.Bind = function (colorCurves, effect) {
  57379. if (colorCurves._dirty) {
  57380. colorCurves._dirty = false;
  57381. // Fill in global info.
  57382. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57383. // Compute highlights info.
  57384. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57385. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57386. // Compute midtones info.
  57387. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57388. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57389. // Compute shadows info.
  57390. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57391. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57392. // Compute deltas (neutral is midtones).
  57393. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57394. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57395. }
  57396. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57397. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57398. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57399. };
  57400. /**
  57401. * Prepare the list of uniforms associated with the ColorCurves effects.
  57402. * @param uniformsList The list of uniforms used in the effect
  57403. */
  57404. ColorCurves.PrepareUniforms = function (uniformsList) {
  57405. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57406. };
  57407. /**
  57408. * Returns color grading data based on a hue, density, saturation and exposure value.
  57409. * @param filterHue The hue of the color filter.
  57410. * @param filterDensity The density of the color filter.
  57411. * @param saturation The saturation.
  57412. * @param exposure The exposure.
  57413. * @param result The result data container.
  57414. */
  57415. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57416. if (hue == null) {
  57417. return;
  57418. }
  57419. hue = ColorCurves.clamp(hue, 0, 360);
  57420. density = ColorCurves.clamp(density, -100, 100);
  57421. saturation = ColorCurves.clamp(saturation, -100, 100);
  57422. exposure = ColorCurves.clamp(exposure, -100, 100);
  57423. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57424. // so that the maximum filter density is only 50% control. This provides fine control
  57425. // for small values and reasonable range.
  57426. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57427. density *= 0.5;
  57428. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57429. if (density < 0) {
  57430. density *= -1;
  57431. hue = (hue + 180) % 360;
  57432. }
  57433. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57434. result.scaleToRef(2, result);
  57435. result.a = 1 + 0.01 * saturation;
  57436. };
  57437. /**
  57438. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57439. * @param value The input slider value in range [-100,100].
  57440. * @returns Adjusted value.
  57441. */
  57442. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57443. value /= 100;
  57444. var x = Math.abs(value);
  57445. x = Math.pow(x, 2);
  57446. if (value < 0) {
  57447. x *= -1;
  57448. }
  57449. x *= 100;
  57450. return x;
  57451. };
  57452. /**
  57453. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57454. * @param hue The hue (H) input.
  57455. * @param saturation The saturation (S) input.
  57456. * @param brightness The brightness (B) input.
  57457. * @result An RGBA color represented as Vector4.
  57458. */
  57459. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57460. var h = ColorCurves.clamp(hue, 0, 360);
  57461. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57462. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57463. if (s === 0) {
  57464. result.r = v;
  57465. result.g = v;
  57466. result.b = v;
  57467. }
  57468. else {
  57469. // sector 0 to 5
  57470. h /= 60;
  57471. var i = Math.floor(h);
  57472. // fractional part of h
  57473. var f = h - i;
  57474. var p = v * (1 - s);
  57475. var q = v * (1 - s * f);
  57476. var t = v * (1 - s * (1 - f));
  57477. switch (i) {
  57478. case 0:
  57479. result.r = v;
  57480. result.g = t;
  57481. result.b = p;
  57482. break;
  57483. case 1:
  57484. result.r = q;
  57485. result.g = v;
  57486. result.b = p;
  57487. break;
  57488. case 2:
  57489. result.r = p;
  57490. result.g = v;
  57491. result.b = t;
  57492. break;
  57493. case 3:
  57494. result.r = p;
  57495. result.g = q;
  57496. result.b = v;
  57497. break;
  57498. case 4:
  57499. result.r = t;
  57500. result.g = p;
  57501. result.b = v;
  57502. break;
  57503. default:
  57504. result.r = v;
  57505. result.g = p;
  57506. result.b = q;
  57507. break;
  57508. }
  57509. }
  57510. result.a = 1;
  57511. };
  57512. /**
  57513. * Returns a value clamped between min and max
  57514. * @param value The value to clamp
  57515. * @param min The minimum of value
  57516. * @param max The maximum of value
  57517. * @returns The clamped value.
  57518. */
  57519. ColorCurves.clamp = function (value, min, max) {
  57520. return Math.min(Math.max(value, min), max);
  57521. };
  57522. /**
  57523. * Clones the current color curve instance.
  57524. * @return The cloned curves
  57525. */
  57526. ColorCurves.prototype.clone = function () {
  57527. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57528. };
  57529. /**
  57530. * Serializes the current color curve instance to a json representation.
  57531. * @return a JSON representation
  57532. */
  57533. ColorCurves.prototype.serialize = function () {
  57534. return BABYLON.SerializationHelper.Serialize(this);
  57535. };
  57536. /**
  57537. * Parses the color curve from a json representation.
  57538. * @param source the JSON source to parse
  57539. * @return The parsed curves
  57540. */
  57541. ColorCurves.Parse = function (source) {
  57542. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57543. };
  57544. __decorate([
  57545. BABYLON.serialize()
  57546. ], ColorCurves.prototype, "_globalHue", void 0);
  57547. __decorate([
  57548. BABYLON.serialize()
  57549. ], ColorCurves.prototype, "_globalDensity", void 0);
  57550. __decorate([
  57551. BABYLON.serialize()
  57552. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57553. __decorate([
  57554. BABYLON.serialize()
  57555. ], ColorCurves.prototype, "_globalExposure", void 0);
  57556. __decorate([
  57557. BABYLON.serialize()
  57558. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57559. __decorate([
  57560. BABYLON.serialize()
  57561. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57562. __decorate([
  57563. BABYLON.serialize()
  57564. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57565. __decorate([
  57566. BABYLON.serialize()
  57567. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57568. __decorate([
  57569. BABYLON.serialize()
  57570. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57571. __decorate([
  57572. BABYLON.serialize()
  57573. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57574. __decorate([
  57575. BABYLON.serialize()
  57576. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57577. __decorate([
  57578. BABYLON.serialize()
  57579. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57580. return ColorCurves;
  57581. })();
  57582. BABYLON.ColorCurves = ColorCurves;
  57583. })(BABYLON || (BABYLON = {}));
  57584. var BABYLON;
  57585. (function (BABYLON) {
  57586. /**
  57587. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57588. * It can help converting any input color in a desired output one. This can then be used to create effects
  57589. * from sepia, black and white to sixties or futuristic rendering...
  57590. *
  57591. * The only supported format is currently 3dl.
  57592. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57593. */
  57594. var ColorGradingTexture = (function (_super) {
  57595. __extends(ColorGradingTexture, _super);
  57596. /**
  57597. * Instantiates a ColorGradingTexture from the following parameters.
  57598. *
  57599. * @param url The location of the color gradind data (currently only supporting 3dl)
  57600. * @param scene The scene the texture will be used in
  57601. */
  57602. function ColorGradingTexture(url, scene) {
  57603. _super.call(this, scene);
  57604. if (!url) {
  57605. return;
  57606. }
  57607. this._textureMatrix = BABYLON.Matrix.Identity();
  57608. this.name = url;
  57609. this.url = url;
  57610. this.hasAlpha = false;
  57611. this.isCube = false;
  57612. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57613. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57614. this.anisotropicFilteringLevel = 1;
  57615. this._texture = this._getFromCache(url, true);
  57616. if (!this._texture) {
  57617. if (!scene.useDelayedTextureLoading) {
  57618. this.loadTexture();
  57619. }
  57620. else {
  57621. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57622. }
  57623. }
  57624. }
  57625. /**
  57626. * Returns the texture matrix used in most of the material.
  57627. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57628. */
  57629. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57630. return this._textureMatrix;
  57631. };
  57632. /**
  57633. * Occurs when the file being loaded is a .3dl LUT file.
  57634. */
  57635. ColorGradingTexture.prototype.load3dlTexture = function () {
  57636. var _this = this;
  57637. var mipLevels = 0;
  57638. var floatArrayView = null;
  57639. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57640. this._texture = texture;
  57641. var callback = function (text) {
  57642. var data;
  57643. var tempData;
  57644. var line;
  57645. var lines = text.split('\n');
  57646. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57647. var maxColor = 0;
  57648. for (var i = 0; i < lines.length; i++) {
  57649. line = lines[i];
  57650. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57651. continue;
  57652. if (line.indexOf('#') === 0)
  57653. continue;
  57654. var words = line.split(" ");
  57655. if (size === 0) {
  57656. // Number of space + one
  57657. size = words.length;
  57658. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57659. tempData = new Float32Array(size * size * size * 4);
  57660. continue;
  57661. }
  57662. if (size != 0) {
  57663. var r = Math.max(parseInt(words[0]), 0);
  57664. var g = Math.max(parseInt(words[1]), 0);
  57665. var b = Math.max(parseInt(words[2]), 0);
  57666. maxColor = Math.max(r, maxColor);
  57667. maxColor = Math.max(g, maxColor);
  57668. maxColor = Math.max(b, maxColor);
  57669. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57670. tempData[pixelStorageIndex + 0] = r;
  57671. tempData[pixelStorageIndex + 1] = g;
  57672. tempData[pixelStorageIndex + 2] = b;
  57673. tempData[pixelStorageIndex + 3] = 0;
  57674. pixelIndexSlice++;
  57675. if (pixelIndexSlice % size == 0) {
  57676. pixelIndexH++;
  57677. pixelIndexSlice = 0;
  57678. if (pixelIndexH % size == 0) {
  57679. pixelIndexW++;
  57680. pixelIndexH = 0;
  57681. }
  57682. }
  57683. }
  57684. }
  57685. for (var i = 0; i < tempData.length; i++) {
  57686. var value = tempData[i];
  57687. data[i] = (value / maxColor * 255);
  57688. }
  57689. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57690. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57691. };
  57692. BABYLON.Tools.LoadFile(this.url, callback);
  57693. return this._texture;
  57694. };
  57695. /**
  57696. * Starts the loading process of the texture.
  57697. */
  57698. ColorGradingTexture.prototype.loadTexture = function () {
  57699. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57700. this.load3dlTexture();
  57701. }
  57702. };
  57703. /**
  57704. * Clones the color gradind texture.
  57705. */
  57706. ColorGradingTexture.prototype.clone = function () {
  57707. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57708. // Base texture
  57709. newTexture.level = this.level;
  57710. return newTexture;
  57711. };
  57712. /**
  57713. * Called during delayed load for textures.
  57714. */
  57715. ColorGradingTexture.prototype.delayLoad = function () {
  57716. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57717. return;
  57718. }
  57719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57720. this._texture = this._getFromCache(this.url, true);
  57721. if (!this._texture) {
  57722. this.loadTexture();
  57723. }
  57724. };
  57725. /**
  57726. * Parses a color grading texture serialized by Babylon.
  57727. * @param parsedTexture The texture information being parsedTexture
  57728. * @param scene The scene to load the texture in
  57729. * @param rootUrl The root url of the data assets to load
  57730. * @return A color gradind texture
  57731. */
  57732. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57733. var texture = null;
  57734. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57735. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57736. texture.name = parsedTexture.name;
  57737. texture.level = parsedTexture.level;
  57738. }
  57739. return texture;
  57740. };
  57741. /**
  57742. * Serializes the LUT texture to json format.
  57743. */
  57744. ColorGradingTexture.prototype.serialize = function () {
  57745. if (!this.name) {
  57746. return null;
  57747. }
  57748. var serializationObject = {};
  57749. serializationObject.name = this.name;
  57750. serializationObject.level = this.level;
  57751. return serializationObject;
  57752. };
  57753. /**
  57754. * Empty line regex stored for GC.
  57755. */
  57756. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57757. return ColorGradingTexture;
  57758. })(BABYLON.BaseTexture);
  57759. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57760. })(BABYLON || (BABYLON = {}));
  57761. var BABYLON;
  57762. (function (BABYLON) {
  57763. var PBRMaterialDefines = (function (_super) {
  57764. __extends(PBRMaterialDefines, _super);
  57765. function PBRMaterialDefines() {
  57766. _super.call(this);
  57767. this.ALBEDO = false;
  57768. this.AMBIENT = false;
  57769. this.OPACITY = false;
  57770. this.OPACITYRGB = false;
  57771. this.REFLECTION = false;
  57772. this.EMISSIVE = false;
  57773. this.REFLECTIVITY = false;
  57774. this.BUMP = false;
  57775. this.PARALLAX = false;
  57776. this.PARALLAXOCCLUSION = false;
  57777. this.SPECULAROVERALPHA = false;
  57778. this.CLIPPLANE = false;
  57779. this.ALPHATEST = false;
  57780. this.ALPHAFROMALBEDO = false;
  57781. this.POINTSIZE = false;
  57782. this.FOG = false;
  57783. this.SPECULARTERM = false;
  57784. this.OPACITYFRESNEL = false;
  57785. this.EMISSIVEFRESNEL = false;
  57786. this.FRESNEL = false;
  57787. this.NORMAL = false;
  57788. this.UV1 = false;
  57789. this.UV2 = false;
  57790. this.VERTEXCOLOR = false;
  57791. this.VERTEXALPHA = false;
  57792. this.NUM_BONE_INFLUENCERS = 0;
  57793. this.BonesPerMesh = 0;
  57794. this.INSTANCES = false;
  57795. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57796. this.MICROSURFACEAUTOMATIC = false;
  57797. this.EMISSIVEASILLUMINATION = false;
  57798. this.LINKEMISSIVEWITHALBEDO = false;
  57799. this.LIGHTMAP = false;
  57800. this.USELIGHTMAPASSHADOWMAP = false;
  57801. this.REFLECTIONMAP_3D = false;
  57802. this.REFLECTIONMAP_SPHERICAL = false;
  57803. this.REFLECTIONMAP_PLANAR = false;
  57804. this.REFLECTIONMAP_CUBIC = false;
  57805. this.REFLECTIONMAP_PROJECTION = false;
  57806. this.REFLECTIONMAP_SKYBOX = false;
  57807. this.REFLECTIONMAP_EXPLICIT = false;
  57808. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57809. this.INVERTCUBICMAP = false;
  57810. this.LOGARITHMICDEPTH = false;
  57811. this.CAMERATONEMAP = false;
  57812. this.CAMERACONTRAST = false;
  57813. this.CAMERACOLORGRADING = false;
  57814. this.CAMERACOLORCURVES = false;
  57815. this.OVERLOADEDVALUES = false;
  57816. this.OVERLOADEDSHADOWVALUES = false;
  57817. this.USESPHERICALFROMREFLECTIONMAP = false;
  57818. this.REFRACTION = false;
  57819. this.REFRACTIONMAP_3D = false;
  57820. this.LINKREFRACTIONTOTRANSPARENCY = false;
  57821. this.REFRACTIONMAPINLINEARSPACE = false;
  57822. this.LODBASEDMICROSFURACE = false;
  57823. this.USEPHYSICALLIGHTFALLOFF = false;
  57824. this.RADIANCEOVERALPHA = false;
  57825. this.USEPMREMREFLECTION = false;
  57826. this.USEPMREMREFRACTION = false;
  57827. this.OPENGLNORMALMAP = false;
  57828. this.INVERTNORMALMAPX = false;
  57829. this.INVERTNORMALMAPY = false;
  57830. this.rebuild();
  57831. }
  57832. return PBRMaterialDefines;
  57833. })(BABYLON.MaterialDefines);
  57834. /**
  57835. * The Physically based material of BJS.
  57836. *
  57837. * This offers the main features of a standard PBR material.
  57838. * For more information, please refer to the documentation :
  57839. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  57840. */
  57841. var PBRMaterial = (function (_super) {
  57842. __extends(PBRMaterial, _super);
  57843. /**
  57844. * Instantiates a new PBRMaterial instance.
  57845. *
  57846. * @param name The material name
  57847. * @param scene The scene the material will be use in.
  57848. */
  57849. function PBRMaterial(name, scene) {
  57850. var _this = this;
  57851. _super.call(this, name, scene);
  57852. /**
  57853. * Intensity of the direct lights e.g. the four lights available in your scene.
  57854. * This impacts both the direct diffuse and specular highlights.
  57855. */
  57856. this.directIntensity = 1.0;
  57857. /**
  57858. * Intensity of the emissive part of the material.
  57859. * This helps controlling the emissive effect without modifying the emissive color.
  57860. */
  57861. this.emissiveIntensity = 1.0;
  57862. /**
  57863. * Intensity of the environment e.g. how much the environment will light the object
  57864. * either through harmonics for rough material or through the refelction for shiny ones.
  57865. */
  57866. this.environmentIntensity = 1.0;
  57867. /**
  57868. * This is a special control allowing the reduction of the specular highlights coming from the
  57869. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  57870. */
  57871. this.specularIntensity = 1.0;
  57872. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  57873. /**
  57874. * Debug Control allowing disabling the bump map on this material.
  57875. */
  57876. this.disableBumpMap = false;
  57877. /**
  57878. * Debug Control helping enforcing or dropping the darkness of shadows.
  57879. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  57880. */
  57881. this.overloadedShadowIntensity = 1.0;
  57882. /**
  57883. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  57884. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  57885. */
  57886. this.overloadedShadeIntensity = 1.0;
  57887. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  57888. /**
  57889. * The camera exposure used on this material.
  57890. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  57891. * This corresponds to a photographic exposure.
  57892. */
  57893. this.cameraExposure = 1.0;
  57894. /**
  57895. * The camera contrast used on this material.
  57896. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  57897. */
  57898. this.cameraContrast = 1.0;
  57899. /**
  57900. * Color Grading 2D Lookup Texture.
  57901. * This allows special effects like sepia, black and white to sixties rendering style.
  57902. */
  57903. this.cameraColorGradingTexture = null;
  57904. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57905. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57906. /**
  57907. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57908. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57909. * 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;
  57910. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57911. */
  57912. this.cameraColorCurves = null;
  57913. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57914. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  57915. /**
  57916. * Debug Control allowing to overload the ambient color.
  57917. * This as to be use with the overloadedAmbientIntensity parameter.
  57918. */
  57919. this.overloadedAmbient = BABYLON.Color3.White();
  57920. /**
  57921. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  57922. */
  57923. this.overloadedAmbientIntensity = 0.0;
  57924. /**
  57925. * Debug Control allowing to overload the albedo color.
  57926. * This as to be use with the overloadedAlbedoIntensity parameter.
  57927. */
  57928. this.overloadedAlbedo = BABYLON.Color3.White();
  57929. /**
  57930. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  57931. */
  57932. this.overloadedAlbedoIntensity = 0.0;
  57933. /**
  57934. * Debug Control allowing to overload the reflectivity color.
  57935. * This as to be use with the overloadedReflectivityIntensity parameter.
  57936. */
  57937. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  57938. /**
  57939. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  57940. */
  57941. this.overloadedReflectivityIntensity = 0.0;
  57942. /**
  57943. * Debug Control allowing to overload the emissive color.
  57944. * This as to be use with the overloadedEmissiveIntensity parameter.
  57945. */
  57946. this.overloadedEmissive = BABYLON.Color3.White();
  57947. /**
  57948. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  57949. */
  57950. this.overloadedEmissiveIntensity = 0.0;
  57951. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  57952. /**
  57953. * Debug Control allowing to overload the reflection color.
  57954. * This as to be use with the overloadedReflectionIntensity parameter.
  57955. */
  57956. this.overloadedReflection = BABYLON.Color3.White();
  57957. /**
  57958. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  57959. */
  57960. this.overloadedReflectionIntensity = 0.0;
  57961. /**
  57962. * Debug Control allowing to overload the microsurface.
  57963. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  57964. */
  57965. this.overloadedMicroSurface = 0.0;
  57966. /**
  57967. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  57968. */
  57969. this.overloadedMicroSurfaceIntensity = 0.0;
  57970. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  57971. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  57972. /**
  57973. * AKA Diffuse Color in other nomenclature.
  57974. */
  57975. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  57976. /**
  57977. * AKA Specular Color in other nomenclature.
  57978. */
  57979. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  57980. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  57981. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  57982. /**
  57983. * AKA Glossiness in other nomenclature.
  57984. */
  57985. this.microSurface = 0.9;
  57986. /**
  57987. * source material index of refraction (IOR)' / 'destination material IOR.
  57988. */
  57989. this.indexOfRefraction = 0.66;
  57990. /**
  57991. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  57992. */
  57993. this.invertRefractionY = false;
  57994. /**
  57995. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  57996. * Materials half opaque for instance using refraction could benefit from this control.
  57997. */
  57998. this.linkRefractionWithTransparency = false;
  57999. /**
  58000. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58001. */
  58002. this.linkEmissiveWithAlbedo = false;
  58003. this.useLightmapAsShadowmap = false;
  58004. /**
  58005. * In this mode, the emissive informtaion will always be added to the lighting once.
  58006. * A light for instance can be thought as emissive.
  58007. */
  58008. this.useEmissiveAsIllumination = false;
  58009. /**
  58010. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58011. */
  58012. this.useAlphaFromAlbedoTexture = false;
  58013. /**
  58014. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58015. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58016. */
  58017. this.useSpecularOverAlpha = true;
  58018. /**
  58019. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58020. */
  58021. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58022. /**
  58023. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58024. * The material will try to infer what glossiness each pixel should be.
  58025. */
  58026. this.useAutoMicroSurfaceFromReflectivityMap = false;
  58027. /**
  58028. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58029. * the creation of the material.
  58030. */
  58031. this.useScalarInLinearSpace = false;
  58032. /**
  58033. * BJS is using an harcoded light falloff based on a manually sets up range.
  58034. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58035. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58036. */
  58037. this.usePhysicalLightFalloff = true;
  58038. /**
  58039. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58040. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58041. */
  58042. this.useRadianceOverAlpha = true;
  58043. /**
  58044. * Allows using the bump map in parallax mode.
  58045. */
  58046. this.useParallax = false;
  58047. /**
  58048. * Allows using the bump map in parallax occlusion mode.
  58049. */
  58050. this.useParallaxOcclusion = false;
  58051. /**
  58052. * Controls the scale bias of the parallax mode.
  58053. */
  58054. this.parallaxScaleBias = 0.05;
  58055. /**
  58056. * If sets to true, disables all the lights affecting the material.
  58057. */
  58058. this.disableLighting = false;
  58059. /**
  58060. * Number of Simultaneous lights allowed on the material.
  58061. */
  58062. this.maxSimultaneousLights = 4;
  58063. /**
  58064. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58065. */
  58066. this.invertNormalMapX = false;
  58067. /**
  58068. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58069. */
  58070. this.invertNormalMapY = false;
  58071. this._renderTargets = new BABYLON.SmartArray(16);
  58072. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58073. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58074. this._tempColor = new BABYLON.Color3();
  58075. this._defines = new PBRMaterialDefines();
  58076. this._cachedDefines = new PBRMaterialDefines();
  58077. this._myScene = null;
  58078. this._myShadowGenerator = null;
  58079. this._cachedDefines.BonesPerMesh = -1;
  58080. this.getRenderTargetTextures = function () {
  58081. _this._renderTargets.reset();
  58082. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58083. _this._renderTargets.push(_this.reflectionTexture);
  58084. }
  58085. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58086. _this._renderTargets.push(_this.refractionTexture);
  58087. }
  58088. return _this._renderTargets;
  58089. };
  58090. }
  58091. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58092. get: function () {
  58093. return this._useLogarithmicDepth;
  58094. },
  58095. set: function (value) {
  58096. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58097. },
  58098. enumerable: true,
  58099. configurable: true
  58100. });
  58101. PBRMaterial.prototype.needAlphaBlending = function () {
  58102. if (this.linkRefractionWithTransparency) {
  58103. return false;
  58104. }
  58105. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58106. };
  58107. PBRMaterial.prototype.needAlphaTesting = function () {
  58108. if (this.linkRefractionWithTransparency) {
  58109. return false;
  58110. }
  58111. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58112. };
  58113. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58114. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58115. };
  58116. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58117. return this.albedoTexture;
  58118. };
  58119. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58120. if (!mesh) {
  58121. return true;
  58122. }
  58123. if (this._defines.INSTANCES !== useInstances) {
  58124. return false;
  58125. }
  58126. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58127. return true;
  58128. }
  58129. return false;
  58130. };
  58131. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58132. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58133. };
  58134. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58135. if (!useScalarInLinear) {
  58136. color.toLinearSpaceToRef(ref);
  58137. }
  58138. else {
  58139. ref.r = color.r;
  58140. ref.g = color.g;
  58141. ref.b = color.b;
  58142. }
  58143. };
  58144. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58145. var lightIndex = 0;
  58146. var depthValuesAlreadySet = false;
  58147. for (var index = 0; index < scene.lights.length; index++) {
  58148. var light = scene.lights[index];
  58149. if (!light.isEnabled()) {
  58150. continue;
  58151. }
  58152. if (!light.canAffectMesh(mesh)) {
  58153. continue;
  58154. }
  58155. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58156. // GAMMA CORRECTION.
  58157. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58158. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58159. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58160. if (defines["SPECULARTERM"]) {
  58161. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58162. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58163. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58164. }
  58165. // Shadows
  58166. if (scene.shadowsEnabled) {
  58167. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58168. }
  58169. lightIndex++;
  58170. if (lightIndex === maxSimultaneousLights)
  58171. break;
  58172. }
  58173. };
  58174. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58175. if (this.checkReadyOnlyOnce) {
  58176. if (this._wasPreviouslyReady) {
  58177. return true;
  58178. }
  58179. }
  58180. var scene = this.getScene();
  58181. if (!this.checkReadyOnEveryCall) {
  58182. if (this._renderId === scene.getRenderId()) {
  58183. if (this._checkCache(scene, mesh, useInstances)) {
  58184. return true;
  58185. }
  58186. }
  58187. }
  58188. var engine = scene.getEngine();
  58189. var needNormals = false;
  58190. var needUVs = false;
  58191. this._defines.reset();
  58192. if (scene.texturesEnabled) {
  58193. // Textures
  58194. if (scene.texturesEnabled) {
  58195. if (scene.getEngine().getCaps().textureLOD) {
  58196. this._defines.LODBASEDMICROSFURACE = true;
  58197. }
  58198. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58199. if (!this.albedoTexture.isReady()) {
  58200. return false;
  58201. }
  58202. else {
  58203. needUVs = true;
  58204. this._defines.ALBEDO = true;
  58205. }
  58206. }
  58207. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58208. if (!this.ambientTexture.isReady()) {
  58209. return false;
  58210. }
  58211. else {
  58212. needUVs = true;
  58213. this._defines.AMBIENT = true;
  58214. }
  58215. }
  58216. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58217. if (!this.opacityTexture.isReady()) {
  58218. return false;
  58219. }
  58220. else {
  58221. needUVs = true;
  58222. this._defines.OPACITY = true;
  58223. if (this.opacityTexture.getAlphaFromRGB) {
  58224. this._defines.OPACITYRGB = true;
  58225. }
  58226. }
  58227. }
  58228. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58229. if (!this.reflectionTexture.isReady()) {
  58230. return false;
  58231. }
  58232. else {
  58233. needNormals = true;
  58234. this._defines.REFLECTION = true;
  58235. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58236. this._defines.INVERTCUBICMAP = true;
  58237. }
  58238. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58239. switch (this.reflectionTexture.coordinatesMode) {
  58240. case BABYLON.Texture.CUBIC_MODE:
  58241. case BABYLON.Texture.INVCUBIC_MODE:
  58242. this._defines.REFLECTIONMAP_CUBIC = true;
  58243. break;
  58244. case BABYLON.Texture.EXPLICIT_MODE:
  58245. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58246. break;
  58247. case BABYLON.Texture.PLANAR_MODE:
  58248. this._defines.REFLECTIONMAP_PLANAR = true;
  58249. break;
  58250. case BABYLON.Texture.PROJECTION_MODE:
  58251. this._defines.REFLECTIONMAP_PROJECTION = true;
  58252. break;
  58253. case BABYLON.Texture.SKYBOX_MODE:
  58254. this._defines.REFLECTIONMAP_SKYBOX = true;
  58255. break;
  58256. case BABYLON.Texture.SPHERICAL_MODE:
  58257. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58258. break;
  58259. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58260. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58261. break;
  58262. }
  58263. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58264. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58265. needNormals = true;
  58266. if (this.reflectionTexture.isPMREM) {
  58267. this._defines.USEPMREMREFLECTION = true;
  58268. }
  58269. }
  58270. }
  58271. }
  58272. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58273. if (!this.lightmapTexture.isReady()) {
  58274. return false;
  58275. }
  58276. else {
  58277. needUVs = true;
  58278. this._defines.LIGHTMAP = true;
  58279. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58280. }
  58281. }
  58282. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58283. if (!this.emissiveTexture.isReady()) {
  58284. return false;
  58285. }
  58286. else {
  58287. needUVs = true;
  58288. this._defines.EMISSIVE = true;
  58289. }
  58290. }
  58291. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58292. if (!this.reflectivityTexture.isReady()) {
  58293. return false;
  58294. }
  58295. else {
  58296. needUVs = true;
  58297. this._defines.REFLECTIVITY = true;
  58298. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58299. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58300. }
  58301. }
  58302. }
  58303. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58304. if (!this.bumpTexture.isReady()) {
  58305. return false;
  58306. }
  58307. else {
  58308. needUVs = true;
  58309. this._defines.BUMP = true;
  58310. if (this.useParallax) {
  58311. this._defines.PARALLAX = true;
  58312. if (this.useParallaxOcclusion) {
  58313. this._defines.PARALLAXOCCLUSION = true;
  58314. }
  58315. }
  58316. if (this.invertNormalMapX) {
  58317. this._defines.INVERTNORMALMAPX = true;
  58318. }
  58319. if (this.invertNormalMapY) {
  58320. this._defines.INVERTNORMALMAPY = true;
  58321. }
  58322. }
  58323. }
  58324. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58325. if (!this.refractionTexture.isReady()) {
  58326. return false;
  58327. }
  58328. else {
  58329. needUVs = true;
  58330. this._defines.REFRACTION = true;
  58331. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58332. if (this.linkRefractionWithTransparency) {
  58333. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58334. }
  58335. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58336. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58337. if (this.refractionTexture.isPMREM) {
  58338. this._defines.USEPMREMREFRACTION = true;
  58339. }
  58340. }
  58341. }
  58342. }
  58343. if (this.cameraColorGradingTexture) {
  58344. if (!this.cameraColorGradingTexture.isReady()) {
  58345. return false;
  58346. }
  58347. else {
  58348. this._defines.CAMERACOLORGRADING = true;
  58349. }
  58350. }
  58351. }
  58352. // Effect
  58353. if (scene.clipPlane) {
  58354. this._defines.CLIPPLANE = true;
  58355. }
  58356. if (engine.getAlphaTesting()) {
  58357. this._defines.ALPHATEST = true;
  58358. }
  58359. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58360. this._defines.ALPHAFROMALBEDO = true;
  58361. }
  58362. if (this.useEmissiveAsIllumination) {
  58363. this._defines.EMISSIVEASILLUMINATION = true;
  58364. }
  58365. if (this.linkEmissiveWithAlbedo) {
  58366. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58367. }
  58368. if (this.useLogarithmicDepth) {
  58369. this._defines.LOGARITHMICDEPTH = true;
  58370. }
  58371. if (this.cameraContrast != 1) {
  58372. this._defines.CAMERACONTRAST = true;
  58373. }
  58374. if (this.cameraExposure != 1) {
  58375. this._defines.CAMERATONEMAP = true;
  58376. }
  58377. if (this.cameraColorCurves) {
  58378. this._defines.CAMERACOLORCURVES = true;
  58379. }
  58380. if (this.overloadedShadeIntensity != 1 ||
  58381. this.overloadedShadowIntensity != 1) {
  58382. this._defines.OVERLOADEDSHADOWVALUES = true;
  58383. }
  58384. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58385. this.overloadedEmissiveIntensity > 0 ||
  58386. this.overloadedReflectivityIntensity > 0 ||
  58387. this.overloadedAlbedoIntensity > 0 ||
  58388. this.overloadedAmbientIntensity > 0 ||
  58389. this.overloadedReflectionIntensity > 0) {
  58390. this._defines.OVERLOADEDVALUES = true;
  58391. }
  58392. // Point size
  58393. if (this.pointsCloud || scene.forcePointsCloud) {
  58394. this._defines.POINTSIZE = true;
  58395. }
  58396. // Fog
  58397. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58398. this._defines.FOG = true;
  58399. }
  58400. if (scene.lightsEnabled && !this.disableLighting) {
  58401. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58402. }
  58403. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58404. // Fresnel
  58405. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58406. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58407. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58408. this._defines.OPACITYFRESNEL = true;
  58409. }
  58410. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58411. this._defines.EMISSIVEFRESNEL = true;
  58412. }
  58413. needNormals = true;
  58414. this._defines.FRESNEL = true;
  58415. }
  58416. }
  58417. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58418. this._defines.SPECULAROVERALPHA = true;
  58419. }
  58420. if (this.usePhysicalLightFalloff) {
  58421. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58422. }
  58423. if (this.useRadianceOverAlpha) {
  58424. this._defines.RADIANCEOVERALPHA = true;
  58425. }
  58426. // Attribs
  58427. if (mesh) {
  58428. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58429. this._defines.NORMAL = true;
  58430. }
  58431. if (needUVs) {
  58432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58433. this._defines.UV1 = true;
  58434. }
  58435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58436. this._defines.UV2 = true;
  58437. }
  58438. }
  58439. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58440. this._defines.VERTEXCOLOR = true;
  58441. if (mesh.hasVertexAlpha) {
  58442. this._defines.VERTEXALPHA = true;
  58443. }
  58444. }
  58445. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58446. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58447. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58448. }
  58449. // Instances
  58450. if (useInstances) {
  58451. this._defines.INSTANCES = true;
  58452. }
  58453. }
  58454. // Get correct effect
  58455. if (!this._defines.isEqual(this._cachedDefines)) {
  58456. this._defines.cloneTo(this._cachedDefines);
  58457. scene.resetCachedMaterial();
  58458. // Fallbacks
  58459. var fallbacks = new BABYLON.EffectFallbacks();
  58460. if (this._defines.REFLECTION) {
  58461. fallbacks.addFallback(0, "REFLECTION");
  58462. }
  58463. if (this._defines.REFRACTION) {
  58464. fallbacks.addFallback(0, "REFRACTION");
  58465. }
  58466. if (this._defines.REFLECTIVITY) {
  58467. fallbacks.addFallback(0, "REFLECTIVITY");
  58468. }
  58469. if (this._defines.BUMP) {
  58470. fallbacks.addFallback(0, "BUMP");
  58471. }
  58472. if (this._defines.PARALLAX) {
  58473. fallbacks.addFallback(1, "PARALLAX");
  58474. }
  58475. if (this._defines.PARALLAXOCCLUSION) {
  58476. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58477. }
  58478. if (this._defines.SPECULAROVERALPHA) {
  58479. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58480. }
  58481. if (this._defines.FOG) {
  58482. fallbacks.addFallback(1, "FOG");
  58483. }
  58484. if (this._defines.POINTSIZE) {
  58485. fallbacks.addFallback(0, "POINTSIZE");
  58486. }
  58487. if (this._defines.LOGARITHMICDEPTH) {
  58488. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58489. }
  58490. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58491. if (this._defines.SPECULARTERM) {
  58492. fallbacks.addFallback(0, "SPECULARTERM");
  58493. }
  58494. if (this._defines.OPACITYFRESNEL) {
  58495. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58496. }
  58497. if (this._defines.EMISSIVEFRESNEL) {
  58498. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58499. }
  58500. if (this._defines.FRESNEL) {
  58501. fallbacks.addFallback(3, "FRESNEL");
  58502. }
  58503. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58504. fallbacks.addCPUSkinningFallback(0, mesh);
  58505. }
  58506. //Attributes
  58507. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58508. if (this._defines.NORMAL) {
  58509. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58510. }
  58511. if (this._defines.UV1) {
  58512. attribs.push(BABYLON.VertexBuffer.UVKind);
  58513. }
  58514. if (this._defines.UV2) {
  58515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58516. }
  58517. if (this._defines.VERTEXCOLOR) {
  58518. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58519. }
  58520. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58521. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58522. // Legacy browser patch
  58523. var shaderName = "pbr";
  58524. if (!scene.getEngine().getCaps().standardDerivatives) {
  58525. shaderName = "legacypbr";
  58526. }
  58527. var join = this._defines.toString();
  58528. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58529. "vFogInfos", "vFogColor", "pointSize",
  58530. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58531. "mBones",
  58532. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58533. "depthValues",
  58534. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58535. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58536. "logarithmicDepthConstant",
  58537. "vSphericalX", "vSphericalY", "vSphericalZ",
  58538. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58539. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58540. "vMicrosurfaceTextureLods",
  58541. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  58542. ];
  58543. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  58544. "cameraColorGrading2DSampler"];
  58545. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58547. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58548. }
  58549. if (!this._effect.isReady()) {
  58550. return false;
  58551. }
  58552. this._renderId = scene.getRenderId();
  58553. this._wasPreviouslyReady = true;
  58554. if (mesh) {
  58555. if (!mesh._materialDefines) {
  58556. mesh._materialDefines = new PBRMaterialDefines();
  58557. }
  58558. this._defines.cloneTo(mesh._materialDefines);
  58559. }
  58560. return true;
  58561. };
  58562. PBRMaterial.prototype.unbind = function () {
  58563. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58564. this._effect.setTexture("reflection2DSampler", null);
  58565. }
  58566. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58567. this._effect.setTexture("refraction2DSampler", null);
  58568. }
  58569. _super.prototype.unbind.call(this);
  58570. };
  58571. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58572. this._effect.setMatrix("world", world);
  58573. };
  58574. PBRMaterial.prototype.bind = function (world, mesh) {
  58575. this._myScene = this.getScene();
  58576. // Matrices
  58577. this.bindOnlyWorldMatrix(world);
  58578. // Bones
  58579. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58580. if (this._myScene.getCachedMaterial() !== this) {
  58581. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58582. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58583. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58584. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58585. }
  58586. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58587. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58588. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58589. }
  58590. }
  58591. // Textures
  58592. if (this._myScene.texturesEnabled) {
  58593. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58594. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58595. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58596. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58597. }
  58598. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58599. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58600. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  58601. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58602. }
  58603. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58604. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58605. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58606. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58607. }
  58608. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58609. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58610. if (this.reflectionTexture.isCube) {
  58611. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58612. }
  58613. else {
  58614. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58615. }
  58616. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58617. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58618. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58619. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58620. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58621. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58622. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58623. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58624. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58625. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58626. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58627. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58628. }
  58629. }
  58630. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58631. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58632. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58633. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58634. }
  58635. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58636. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58637. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58638. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58639. }
  58640. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58641. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58642. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58643. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58644. }
  58645. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58646. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58647. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58648. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58649. }
  58650. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58651. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58652. var depth = 1.0;
  58653. if (this.refractionTexture.isCube) {
  58654. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58655. }
  58656. else {
  58657. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58658. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58659. if (this.refractionTexture.depth) {
  58660. depth = this.refractionTexture.depth;
  58661. }
  58662. }
  58663. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58664. }
  58665. if ((this.reflectionTexture || this.refractionTexture)) {
  58666. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58667. }
  58668. if (this.cameraColorGradingTexture) {
  58669. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  58670. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  58671. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  58672. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  58673. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  58674. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  58675. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  58676. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  58677. this._cameraColorGradingScaleOffset.x = this._cameraColorGradingInfos.z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  58678. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  58679. this._cameraColorGradingInfos.y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  58680. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58681. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58682. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  58683. }
  58684. }
  58685. // Clip plane
  58686. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58687. // Point size
  58688. if (this.pointsCloud) {
  58689. this._effect.setFloat("pointSize", this.pointSize);
  58690. }
  58691. // Colors
  58692. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58693. // GAMMA CORRECTION.
  58694. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58695. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58696. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58697. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58698. // GAMMA CORRECTION.
  58699. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58700. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58701. // GAMMA CORRECTION.
  58702. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58703. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58704. }
  58705. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  58706. // GAMMA CORRECTION.
  58707. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  58708. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  58709. // Lights
  58710. if (this._myScene.lightsEnabled && !this.disableLighting) {
  58711. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  58712. }
  58713. // View
  58714. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58715. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58716. }
  58717. // Fog
  58718. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58719. this._lightingInfos.x = this.directIntensity;
  58720. this._lightingInfos.y = this.emissiveIntensity;
  58721. this._lightingInfos.z = this.environmentIntensity;
  58722. this._lightingInfos.w = this.specularIntensity;
  58723. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58724. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58725. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58726. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58727. this._cameraInfos.x = this.cameraExposure;
  58728. this._cameraInfos.y = this.cameraContrast;
  58729. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58730. if (this.cameraColorCurves) {
  58731. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58732. }
  58733. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58734. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58735. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58736. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58737. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58738. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  58739. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  58740. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58741. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58742. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58743. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58744. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58745. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58746. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58747. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58748. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58749. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58750. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58751. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58752. // Log. depth
  58753. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58754. }
  58755. _super.prototype.bind.call(this, world, mesh);
  58756. this._myScene = null;
  58757. };
  58758. PBRMaterial.prototype.getAnimatables = function () {
  58759. var results = [];
  58760. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58761. results.push(this.albedoTexture);
  58762. }
  58763. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58764. results.push(this.ambientTexture);
  58765. }
  58766. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58767. results.push(this.opacityTexture);
  58768. }
  58769. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58770. results.push(this.reflectionTexture);
  58771. }
  58772. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58773. results.push(this.emissiveTexture);
  58774. }
  58775. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58776. results.push(this.reflectivityTexture);
  58777. }
  58778. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58779. results.push(this.bumpTexture);
  58780. }
  58781. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58782. results.push(this.lightmapTexture);
  58783. }
  58784. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58785. results.push(this.refractionTexture);
  58786. }
  58787. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  58788. results.push(this.cameraColorGradingTexture);
  58789. }
  58790. return results;
  58791. };
  58792. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58793. if (forceDisposeTextures) {
  58794. if (this.albedoTexture) {
  58795. this.albedoTexture.dispose();
  58796. }
  58797. if (this.ambientTexture) {
  58798. this.ambientTexture.dispose();
  58799. }
  58800. if (this.opacityTexture) {
  58801. this.opacityTexture.dispose();
  58802. }
  58803. if (this.reflectionTexture) {
  58804. this.reflectionTexture.dispose();
  58805. }
  58806. if (this.emissiveTexture) {
  58807. this.emissiveTexture.dispose();
  58808. }
  58809. if (this.reflectivityTexture) {
  58810. this.reflectivityTexture.dispose();
  58811. }
  58812. if (this.bumpTexture) {
  58813. this.bumpTexture.dispose();
  58814. }
  58815. if (this.lightmapTexture) {
  58816. this.lightmapTexture.dispose();
  58817. }
  58818. if (this.refractionTexture) {
  58819. this.refractionTexture.dispose();
  58820. }
  58821. if (this.cameraColorGradingTexture) {
  58822. this.cameraColorGradingTexture.dispose();
  58823. }
  58824. }
  58825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58826. };
  58827. PBRMaterial.prototype.clone = function (name) {
  58828. var _this = this;
  58829. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  58830. };
  58831. PBRMaterial.prototype.serialize = function () {
  58832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58833. serializationObject.customType = "BABYLON.PBRMaterial";
  58834. return serializationObject;
  58835. };
  58836. // Statics
  58837. PBRMaterial.Parse = function (source, scene, rootUrl) {
  58838. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  58839. };
  58840. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  58841. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  58842. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  58843. PBRMaterial._scaledReflection = new BABYLON.Color3();
  58844. __decorate([
  58845. BABYLON.serialize()
  58846. ], PBRMaterial.prototype, "directIntensity", void 0);
  58847. __decorate([
  58848. BABYLON.serialize()
  58849. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  58850. __decorate([
  58851. BABYLON.serialize()
  58852. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  58853. __decorate([
  58854. BABYLON.serialize()
  58855. ], PBRMaterial.prototype, "specularIntensity", void 0);
  58856. __decorate([
  58857. BABYLON.serialize()
  58858. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  58859. __decorate([
  58860. BABYLON.serialize()
  58861. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  58862. __decorate([
  58863. BABYLON.serialize()
  58864. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  58865. __decorate([
  58866. BABYLON.serialize()
  58867. ], PBRMaterial.prototype, "cameraExposure", void 0);
  58868. __decorate([
  58869. BABYLON.serialize()
  58870. ], PBRMaterial.prototype, "cameraContrast", void 0);
  58871. __decorate([
  58872. BABYLON.serializeAsTexture()
  58873. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  58874. __decorate([
  58875. BABYLON.serializeAsColorCurves()
  58876. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  58877. __decorate([
  58878. BABYLON.serializeAsColor3()
  58879. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  58880. __decorate([
  58881. BABYLON.serialize()
  58882. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  58883. __decorate([
  58884. BABYLON.serializeAsColor3()
  58885. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  58886. __decorate([
  58887. BABYLON.serialize()
  58888. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  58889. __decorate([
  58890. BABYLON.serializeAsColor3()
  58891. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  58892. __decorate([
  58893. BABYLON.serialize()
  58894. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  58895. __decorate([
  58896. BABYLON.serializeAsColor3()
  58897. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  58898. __decorate([
  58899. BABYLON.serialize()
  58900. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  58901. __decorate([
  58902. BABYLON.serializeAsColor3()
  58903. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  58904. __decorate([
  58905. BABYLON.serialize()
  58906. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  58907. __decorate([
  58908. BABYLON.serialize()
  58909. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  58910. __decorate([
  58911. BABYLON.serialize()
  58912. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  58913. __decorate([
  58914. BABYLON.serializeAsTexture()
  58915. ], PBRMaterial.prototype, "albedoTexture", void 0);
  58916. __decorate([
  58917. BABYLON.serializeAsTexture()
  58918. ], PBRMaterial.prototype, "ambientTexture", void 0);
  58919. __decorate([
  58920. BABYLON.serializeAsTexture()
  58921. ], PBRMaterial.prototype, "opacityTexture", void 0);
  58922. __decorate([
  58923. BABYLON.serializeAsTexture()
  58924. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  58925. __decorate([
  58926. BABYLON.serializeAsTexture()
  58927. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  58928. __decorate([
  58929. BABYLON.serializeAsTexture()
  58930. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  58931. __decorate([
  58932. BABYLON.serializeAsTexture()
  58933. ], PBRMaterial.prototype, "bumpTexture", void 0);
  58934. __decorate([
  58935. BABYLON.serializeAsTexture()
  58936. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  58937. __decorate([
  58938. BABYLON.serializeAsTexture()
  58939. ], PBRMaterial.prototype, "refractionTexture", void 0);
  58940. __decorate([
  58941. BABYLON.serializeAsColor3("ambient")
  58942. ], PBRMaterial.prototype, "ambientColor", void 0);
  58943. __decorate([
  58944. BABYLON.serializeAsColor3("albedo")
  58945. ], PBRMaterial.prototype, "albedoColor", void 0);
  58946. __decorate([
  58947. BABYLON.serializeAsColor3("reflectivity")
  58948. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  58949. __decorate([
  58950. BABYLON.serializeAsColor3("reflection")
  58951. ], PBRMaterial.prototype, "reflectionColor", void 0);
  58952. __decorate([
  58953. BABYLON.serializeAsColor3("emissive")
  58954. ], PBRMaterial.prototype, "emissiveColor", void 0);
  58955. __decorate([
  58956. BABYLON.serialize()
  58957. ], PBRMaterial.prototype, "microSurface", void 0);
  58958. __decorate([
  58959. BABYLON.serialize()
  58960. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  58961. __decorate([
  58962. BABYLON.serialize()
  58963. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  58964. __decorate([
  58965. BABYLON.serializeAsFresnelParameters()
  58966. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  58967. __decorate([
  58968. BABYLON.serializeAsFresnelParameters()
  58969. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  58970. __decorate([
  58971. BABYLON.serialize()
  58972. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  58973. __decorate([
  58974. BABYLON.serialize()
  58975. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  58976. __decorate([
  58977. BABYLON.serialize()
  58978. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  58979. __decorate([
  58980. BABYLON.serialize()
  58981. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  58982. __decorate([
  58983. BABYLON.serialize()
  58984. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  58985. __decorate([
  58986. BABYLON.serialize()
  58987. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  58988. __decorate([
  58989. BABYLON.serialize()
  58990. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  58991. __decorate([
  58992. BABYLON.serialize()
  58993. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  58994. __decorate([
  58995. BABYLON.serialize()
  58996. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  58997. __decorate([
  58998. BABYLON.serialize()
  58999. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59000. __decorate([
  59001. BABYLON.serialize()
  59002. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59003. __decorate([
  59004. BABYLON.serialize()
  59005. ], PBRMaterial.prototype, "useParallax", void 0);
  59006. __decorate([
  59007. BABYLON.serialize()
  59008. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59009. __decorate([
  59010. BABYLON.serialize()
  59011. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59012. __decorate([
  59013. BABYLON.serialize()
  59014. ], PBRMaterial.prototype, "disableLighting", void 0);
  59015. __decorate([
  59016. BABYLON.serialize()
  59017. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59018. __decorate([
  59019. BABYLON.serialize()
  59020. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59021. __decorate([
  59022. BABYLON.serialize()
  59023. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59024. __decorate([
  59025. BABYLON.serialize()
  59026. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59027. return PBRMaterial;
  59028. })(BABYLON.Material);
  59029. BABYLON.PBRMaterial = PBRMaterial;
  59030. })(BABYLON || (BABYLON = {}));
  59031. var BABYLON;
  59032. (function (BABYLON) {
  59033. var DebugLayer = (function () {
  59034. function DebugLayer(scene) {
  59035. var _this = this;
  59036. this._transformationMatrix = BABYLON.Matrix.Identity();
  59037. this._enabled = false;
  59038. this._labelsEnabled = false;
  59039. this._displayStatistics = true;
  59040. this._displayTree = false;
  59041. this._displayLogs = false;
  59042. this._skeletonViewers = new Array();
  59043. this._identityMatrix = BABYLON.Matrix.Identity();
  59044. this.axisRatio = 0.02;
  59045. this.accentColor = "orange";
  59046. this._scene = scene;
  59047. this._syncPositions = function () {
  59048. var engine = _this._scene.getEngine();
  59049. var canvasRect = engine.getRenderingCanvasClientRect();
  59050. if (_this._showUI) {
  59051. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  59052. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  59053. _this._statsDiv.style.width = "400px";
  59054. _this._statsDiv.style.height = "auto";
  59055. _this._statsSubsetDiv.style.maxHeight = "240px";
  59056. _this._optionsDiv.style.left = "0px";
  59057. _this._optionsDiv.style.top = "10px";
  59058. _this._optionsDiv.style.width = "200px";
  59059. _this._optionsDiv.style.height = "auto";
  59060. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  59061. _this._logDiv.style.left = "0px";
  59062. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  59063. _this._logDiv.style.width = "600px";
  59064. _this._logDiv.style.height = "160px";
  59065. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  59066. _this._treeDiv.style.top = "10px";
  59067. _this._treeDiv.style.width = "300px";
  59068. _this._treeDiv.style.height = "auto";
  59069. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  59070. }
  59071. _this._globalDiv.style.left = canvasRect.left + "px";
  59072. _this._globalDiv.style.top = canvasRect.top + "px";
  59073. _this._drawingCanvas.style.left = "0px";
  59074. _this._drawingCanvas.style.top = "0px";
  59075. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  59076. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  59077. var devicePixelRatio = window.devicePixelRatio || 1;
  59078. var context = _this._drawingContext;
  59079. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  59080. context.mozBackingStorePixelRatio ||
  59081. context.msBackingStorePixelRatio ||
  59082. context.oBackingStorePixelRatio ||
  59083. context.backingStorePixelRatio || 1;
  59084. _this._ratio = devicePixelRatio / backingStoreRatio;
  59085. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  59086. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  59087. };
  59088. this._onCanvasClick = function (evt) {
  59089. _this._clickPosition = {
  59090. x: evt.clientX * _this._ratio,
  59091. y: evt.clientY * _this._ratio
  59092. };
  59093. };
  59094. this._syncUI = function () {
  59095. if (_this._showUI) {
  59096. if (_this._displayStatistics) {
  59097. _this._displayStats();
  59098. _this._statsDiv.style.display = "";
  59099. }
  59100. else {
  59101. _this._statsDiv.style.display = "none";
  59102. }
  59103. if (_this._displayLogs) {
  59104. _this._logDiv.style.display = "";
  59105. }
  59106. else {
  59107. _this._logDiv.style.display = "none";
  59108. }
  59109. if (_this._displayTree) {
  59110. _this._treeDiv.style.display = "";
  59111. if (_this._needToRefreshMeshesTree) {
  59112. _this._needToRefreshMeshesTree = false;
  59113. _this._refreshMeshesTreeContent();
  59114. }
  59115. }
  59116. else {
  59117. _this._treeDiv.style.display = "none";
  59118. }
  59119. }
  59120. };
  59121. this._syncData = function () {
  59122. if (_this._labelsEnabled || !_this._showUI) {
  59123. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  59124. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  59125. var engine = _this._scene.getEngine();
  59126. var viewport = _this._camera.viewport;
  59127. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59128. // Meshes
  59129. var meshes = _this._camera.getActiveMeshes();
  59130. var index;
  59131. var projectedPosition;
  59132. for (index = 0; index < meshes.length; index++) {
  59133. var mesh = meshes.data[index];
  59134. var position = mesh.getBoundingInfo().boundingSphere.center;
  59135. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  59136. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  59137. _this._renderAxis(projectedPosition, mesh, globalViewport);
  59138. }
  59139. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  59140. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  59141. }
  59142. }
  59143. // Cameras
  59144. var cameras = _this._scene.cameras;
  59145. for (index = 0; index < cameras.length; index++) {
  59146. var camera = cameras[index];
  59147. if (camera === _this._camera) {
  59148. continue;
  59149. }
  59150. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  59151. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  59152. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  59153. _this._camera.detachControl(engine.getRenderingCanvas());
  59154. _this._camera = camera;
  59155. _this._camera.attachControl(engine.getRenderingCanvas());
  59156. }, function () { return "purple"; });
  59157. }
  59158. }
  59159. // Lights
  59160. var lights = _this._scene.lights;
  59161. for (index = 0; index < lights.length; index++) {
  59162. var light = lights[index];
  59163. if (light.position) {
  59164. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  59165. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  59166. _this._renderLabel(light.name, projectedPosition, -20, function () {
  59167. light.setEnabled(!light.isEnabled());
  59168. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  59169. }
  59170. }
  59171. }
  59172. }
  59173. _this._clickPosition = undefined;
  59174. };
  59175. }
  59176. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  59177. while (this._treeSubsetDiv.hasChildNodes()) {
  59178. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  59179. }
  59180. // Add meshes
  59181. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  59182. sortedArray.sort(function (a, b) {
  59183. if (a.name === b.name) {
  59184. return 0;
  59185. }
  59186. return (a.name > b.name) ? 1 : -1;
  59187. });
  59188. for (var index = 0; index < sortedArray.length; index++) {
  59189. var mesh = sortedArray[index];
  59190. if (!mesh.isEnabled()) {
  59191. continue;
  59192. }
  59193. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  59194. m.isVisible = element.checked;
  59195. }, mesh);
  59196. }
  59197. };
  59198. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  59199. this._drawingContext.beginPath();
  59200. this._drawingContext.moveTo(zero.x, zero.y);
  59201. this._drawingContext.lineTo(unit.x, unit.y);
  59202. this._drawingContext.strokeStyle = color;
  59203. this._drawingContext.lineWidth = 4;
  59204. this._drawingContext.stroke();
  59205. this._drawingContext.font = "normal 14px Segoe UI";
  59206. this._drawingContext.fillStyle = color;
  59207. this._drawingContext.fillText(label, unitText.x, unitText.y);
  59208. };
  59209. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  59210. var position = mesh.getBoundingInfo().boundingSphere.center;
  59211. var worldMatrix = mesh.getWorldMatrix();
  59212. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  59213. var unit = (unprojectedVector.subtract(position)).length();
  59214. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  59215. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  59216. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  59217. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  59218. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  59219. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  59220. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  59221. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  59222. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  59223. };
  59224. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  59225. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  59226. this._drawingContext.font = "normal 12px Segoe UI";
  59227. var textMetrics = this._drawingContext.measureText(text);
  59228. var centerX = projectedPosition.x - textMetrics.width / 2;
  59229. var centerY = projectedPosition.y;
  59230. var clientRect = this._drawingCanvas.getBoundingClientRect();
  59231. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  59232. onClick();
  59233. }
  59234. this._drawingContext.beginPath();
  59235. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  59236. this._drawingContext.fillStyle = getFillStyle();
  59237. this._drawingContext.globalAlpha = 0.5;
  59238. this._drawingContext.fill();
  59239. this._drawingContext.globalAlpha = 1.0;
  59240. this._drawingContext.strokeStyle = '#FFFFFF';
  59241. this._drawingContext.lineWidth = 1;
  59242. this._drawingContext.stroke();
  59243. this._drawingContext.fillStyle = "#FFFFFF";
  59244. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  59245. this._drawingContext.beginPath();
  59246. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  59247. this._drawingContext.fill();
  59248. }
  59249. };
  59250. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  59251. if (!this._clickPosition) {
  59252. return false;
  59253. }
  59254. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  59255. return false;
  59256. }
  59257. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  59258. return false;
  59259. }
  59260. return true;
  59261. };
  59262. DebugLayer.prototype.isVisible = function () {
  59263. return this._enabled;
  59264. };
  59265. DebugLayer.prototype.hide = function () {
  59266. if (!this._enabled) {
  59267. return;
  59268. }
  59269. this._enabled = false;
  59270. var engine = this._scene.getEngine();
  59271. this._scene.unregisterBeforeRender(this._syncData);
  59272. this._scene.unregisterAfterRender(this._syncUI);
  59273. this._rootElement.removeChild(this._globalDiv);
  59274. this._scene.forceShowBoundingBoxes = false;
  59275. this._scene.forceWireframe = false;
  59276. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  59277. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  59278. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  59279. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  59280. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  59281. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  59282. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  59283. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  59284. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  59285. this._scene.shadowsEnabled = true;
  59286. this._scene.particlesEnabled = true;
  59287. this._scene.postProcessesEnabled = true;
  59288. this._scene.collisionsEnabled = true;
  59289. this._scene.lightsEnabled = true;
  59290. this._scene.texturesEnabled = true;
  59291. this._scene.lensFlaresEnabled = true;
  59292. this._scene.proceduralTexturesEnabled = true;
  59293. this._scene.renderTargetsEnabled = true;
  59294. this._scene.probesEnabled = true;
  59295. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  59296. this._clearSkeletonViewers();
  59297. };
  59298. DebugLayer.prototype._clearSkeletonViewers = function () {
  59299. for (var index = 0; index < this._skeletonViewers.length; index++) {
  59300. this._skeletonViewers[index].dispose();
  59301. }
  59302. this._skeletonViewers = [];
  59303. };
  59304. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  59305. if (showUI === void 0) { showUI = true; }
  59306. if (camera === void 0) { camera = null; }
  59307. if (rootElement === void 0) { rootElement = null; }
  59308. if (this._enabled) {
  59309. return;
  59310. }
  59311. this._enabled = true;
  59312. if (camera) {
  59313. this._camera = camera;
  59314. }
  59315. else {
  59316. this._camera = this._scene.activeCamera;
  59317. }
  59318. this._showUI = showUI;
  59319. var engine = this._scene.getEngine();
  59320. this._globalDiv = document.createElement("div");
  59321. this._rootElement = rootElement || document.body;
  59322. this._rootElement.appendChild(this._globalDiv);
  59323. this._generateDOMelements();
  59324. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  59325. this._syncPositions();
  59326. this._scene.registerBeforeRender(this._syncData);
  59327. this._scene.registerAfterRender(this._syncUI);
  59328. };
  59329. DebugLayer.prototype._clearLabels = function () {
  59330. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  59331. for (var index = 0; index < this._scene.meshes.length; index++) {
  59332. var mesh = this._scene.meshes[index];
  59333. mesh.renderOverlay = false;
  59334. }
  59335. };
  59336. DebugLayer.prototype._generateheader = function (root, text) {
  59337. var header = document.createElement("div");
  59338. header.innerHTML = text + "&nbsp;";
  59339. header.style.textAlign = "right";
  59340. header.style.width = "100%";
  59341. header.style.color = "white";
  59342. header.style.backgroundColor = "Black";
  59343. header.style.padding = "5px 5px 4px 0px";
  59344. header.style.marginLeft = "-5px";
  59345. header.style.fontWeight = "bold";
  59346. root.appendChild(header);
  59347. };
  59348. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  59349. var label = document.createElement("label");
  59350. label.style.display = "inline";
  59351. label.innerHTML = title;
  59352. label.style.color = color;
  59353. root.appendChild(label);
  59354. root.appendChild(document.createElement("br"));
  59355. };
  59356. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  59357. if (tag === void 0) { tag = null; }
  59358. var label = document.createElement("label");
  59359. label.style.display = "inline";
  59360. var boundingBoxesCheckbox = document.createElement("input");
  59361. boundingBoxesCheckbox.type = "checkbox";
  59362. boundingBoxesCheckbox.checked = initialState;
  59363. boundingBoxesCheckbox.style.display = "inline";
  59364. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  59365. boundingBoxesCheckbox.style.verticalAlign = "sub";
  59366. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  59367. task(evt.target, tag);
  59368. });
  59369. label.appendChild(boundingBoxesCheckbox);
  59370. var container = document.createElement("span");
  59371. var leftPart = document.createElement("span");
  59372. var rightPart = document.createElement("span");
  59373. rightPart.style.cssFloat = "right";
  59374. leftPart.innerHTML = leftTitle;
  59375. rightPart.innerHTML = rightTitle;
  59376. rightPart.style.fontSize = "12px";
  59377. rightPart.style.maxWidth = "200px";
  59378. container.appendChild(leftPart);
  59379. container.appendChild(rightPart);
  59380. label.appendChild(container);
  59381. root.appendChild(label);
  59382. root.appendChild(document.createElement("br"));
  59383. };
  59384. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  59385. if (tag === void 0) { tag = null; }
  59386. var label = document.createElement("label");
  59387. label.style.display = "inline";
  59388. var checkBox = document.createElement("input");
  59389. checkBox.type = "checkbox";
  59390. checkBox.checked = initialState;
  59391. checkBox.style.display = "inline";
  59392. checkBox.style.margin = "0px 5px 0px 0px";
  59393. checkBox.style.verticalAlign = "sub";
  59394. checkBox.addEventListener("change", function (evt) {
  59395. task(evt.target, tag);
  59396. });
  59397. label.appendChild(checkBox);
  59398. label.appendChild(document.createTextNode(title));
  59399. root.appendChild(label);
  59400. root.appendChild(document.createElement("br"));
  59401. };
  59402. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  59403. if (tag === void 0) { tag = null; }
  59404. var button = document.createElement("button");
  59405. button.innerHTML = title;
  59406. button.style.height = "24px";
  59407. button.style.width = "150px";
  59408. button.style.marginBottom = "5px";
  59409. button.style.color = "#444444";
  59410. button.style.border = "1px solid white";
  59411. button.className = "debugLayerButton";
  59412. button.addEventListener("click", function (evt) {
  59413. task(evt.target, tag);
  59414. });
  59415. root.appendChild(button);
  59416. root.appendChild(document.createElement("br"));
  59417. };
  59418. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  59419. if (tag === void 0) { tag = null; }
  59420. var label = document.createElement("label");
  59421. label.style.display = "inline";
  59422. var boundingBoxesRadio = document.createElement("input");
  59423. boundingBoxesRadio.type = "radio";
  59424. boundingBoxesRadio.name = name;
  59425. boundingBoxesRadio.checked = initialState;
  59426. boundingBoxesRadio.style.display = "inline";
  59427. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  59428. boundingBoxesRadio.style.verticalAlign = "sub";
  59429. boundingBoxesRadio.addEventListener("change", function (evt) {
  59430. task(evt.target, tag);
  59431. });
  59432. label.appendChild(boundingBoxesRadio);
  59433. label.appendChild(document.createTextNode(title));
  59434. root.appendChild(label);
  59435. root.appendChild(document.createElement("br"));
  59436. };
  59437. DebugLayer.prototype._generateDOMelements = function () {
  59438. var _this = this;
  59439. this._globalDiv.id = "DebugLayer";
  59440. this._globalDiv.style.position = "absolute";
  59441. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  59442. this._globalDiv.style.fontSize = "14px";
  59443. this._globalDiv.style.color = "white";
  59444. // Drawing canvas
  59445. this._drawingCanvas = document.createElement("canvas");
  59446. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  59447. this._drawingCanvas.style.position = "absolute";
  59448. this._drawingCanvas.style.pointerEvents = "none";
  59449. this._drawingCanvas.style.backgroundColor = "transparent";
  59450. this._drawingContext = this._drawingCanvas.getContext("2d");
  59451. this._globalDiv.appendChild(this._drawingCanvas);
  59452. if (this._showUI) {
  59453. var background = "rgba(128, 128, 128, 0.4)";
  59454. var border = "rgb(180, 180, 180) solid 1px";
  59455. // Stats
  59456. this._statsDiv = document.createElement("div");
  59457. this._statsDiv.id = "DebugLayerStats";
  59458. this._statsDiv.style.border = border;
  59459. this._statsDiv.style.position = "absolute";
  59460. this._statsDiv.style.background = background;
  59461. this._statsDiv.style.padding = "0px 0px 0px 5px";
  59462. this._generateheader(this._statsDiv, "STATISTICS");
  59463. this._statsSubsetDiv = document.createElement("div");
  59464. this._statsSubsetDiv.style.paddingTop = "5px";
  59465. this._statsSubsetDiv.style.paddingBottom = "5px";
  59466. this._statsSubsetDiv.style.overflowY = "auto";
  59467. this._statsDiv.appendChild(this._statsSubsetDiv);
  59468. // Tree
  59469. this._treeDiv = document.createElement("div");
  59470. this._treeDiv.id = "DebugLayerTree";
  59471. this._treeDiv.style.border = border;
  59472. this._treeDiv.style.position = "absolute";
  59473. this._treeDiv.style.background = background;
  59474. this._treeDiv.style.padding = "0px 0px 0px 5px";
  59475. this._treeDiv.style.display = "none";
  59476. this._generateheader(this._treeDiv, "MESHES TREE");
  59477. this._treeSubsetDiv = document.createElement("div");
  59478. this._treeSubsetDiv.style.paddingTop = "5px";
  59479. this._treeSubsetDiv.style.paddingRight = "5px";
  59480. this._treeSubsetDiv.style.overflowY = "auto";
  59481. this._treeSubsetDiv.style.maxHeight = "300px";
  59482. this._treeDiv.appendChild(this._treeSubsetDiv);
  59483. this._needToRefreshMeshesTree = true;
  59484. // Logs
  59485. this._logDiv = document.createElement("div");
  59486. this._logDiv.style.border = border;
  59487. this._logDiv.id = "DebugLayerLogs";
  59488. this._logDiv.style.position = "absolute";
  59489. this._logDiv.style.background = background;
  59490. this._logDiv.style.padding = "0px 0px 0px 5px";
  59491. this._logDiv.style.display = "none";
  59492. this._generateheader(this._logDiv, "LOGS");
  59493. this._logSubsetDiv = document.createElement("div");
  59494. this._logSubsetDiv.style.height = "127px";
  59495. this._logSubsetDiv.style.paddingTop = "5px";
  59496. this._logSubsetDiv.style.overflowY = "auto";
  59497. this._logSubsetDiv.style.fontSize = "12px";
  59498. this._logSubsetDiv.style.fontFamily = "consolas";
  59499. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  59500. this._logDiv.appendChild(this._logSubsetDiv);
  59501. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  59502. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  59503. };
  59504. // Options
  59505. this._optionsDiv = document.createElement("div");
  59506. this._optionsDiv.id = "DebugLayerOptions";
  59507. this._optionsDiv.style.border = border;
  59508. this._optionsDiv.style.position = "absolute";
  59509. this._optionsDiv.style.background = background;
  59510. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  59511. this._optionsDiv.style.overflowY = "auto";
  59512. this._generateheader(this._optionsDiv, "OPTIONS");
  59513. this._optionsSubsetDiv = document.createElement("div");
  59514. this._optionsSubsetDiv.style.paddingTop = "5px";
  59515. this._optionsSubsetDiv.style.paddingBottom = "5px";
  59516. this._optionsSubsetDiv.style.overflowY = "auto";
  59517. this._optionsSubsetDiv.style.maxHeight = "200px";
  59518. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  59519. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  59520. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  59521. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  59522. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  59523. _this._displayTree = element.checked;
  59524. _this._needToRefreshMeshesTree = true;
  59525. });
  59526. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59527. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  59528. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  59529. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  59530. _this._labelsEnabled = element.checked;
  59531. if (!_this._labelsEnabled) {
  59532. _this._clearLabels();
  59533. }
  59534. });
  59535. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  59536. if (element.checked) {
  59537. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  59538. }
  59539. else {
  59540. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  59541. }
  59542. });
  59543. ;
  59544. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59545. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  59546. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  59547. if (element.checked) {
  59548. _this._scene.forceWireframe = false;
  59549. _this._scene.forcePointsCloud = false;
  59550. }
  59551. });
  59552. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  59553. if (element.checked) {
  59554. _this._scene.forceWireframe = true;
  59555. _this._scene.forcePointsCloud = false;
  59556. }
  59557. });
  59558. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  59559. if (element.checked) {
  59560. _this._scene.forceWireframe = false;
  59561. _this._scene.forcePointsCloud = true;
  59562. }
  59563. });
  59564. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59565. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  59566. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  59567. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  59568. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  59569. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  59570. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  59571. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  59572. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  59573. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  59574. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  59575. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  59576. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59577. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  59578. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  59579. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  59580. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  59581. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  59582. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  59583. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  59584. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  59585. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  59586. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  59587. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  59588. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  59589. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  59590. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  59591. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  59592. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  59593. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59594. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  59595. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  59596. if (element.checked) {
  59597. _this._scene.headphone = true;
  59598. }
  59599. });
  59600. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  59601. if (element.checked) {
  59602. _this._scene.headphone = false;
  59603. }
  59604. });
  59605. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  59606. _this._scene.audioEnabled = !element.checked;
  59607. });
  59608. }
  59609. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59610. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  59611. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  59612. if (!element.checked) {
  59613. _this._clearSkeletonViewers();
  59614. return;
  59615. }
  59616. for (var index = 0; index < _this._scene.meshes.length; index++) {
  59617. var mesh = _this._scene.meshes[index];
  59618. if (mesh.skeleton) {
  59619. var found = false;
  59620. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  59621. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  59622. found = true;
  59623. break;
  59624. }
  59625. }
  59626. if (found) {
  59627. continue;
  59628. }
  59629. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  59630. viewer.isEnabled = true;
  59631. _this._skeletonViewers.push(viewer);
  59632. }
  59633. }
  59634. });
  59635. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59636. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  59637. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  59638. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  59639. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  59640. if (_this._camera) {
  59641. console.log(_this._camera);
  59642. }
  59643. else {
  59644. console.warn("No camera defined, or debug layer created before camera creation!");
  59645. }
  59646. });
  59647. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  59648. this._globalDiv.appendChild(this._statsDiv);
  59649. this._globalDiv.appendChild(this._logDiv);
  59650. this._globalDiv.appendChild(this._optionsDiv);
  59651. this._globalDiv.appendChild(this._treeDiv);
  59652. }
  59653. };
  59654. DebugLayer.prototype._displayStats = function () {
  59655. var scene = this._scene;
  59656. var engine = scene.getEngine();
  59657. var glInfo = engine.getGlInfo();
  59658. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  59659. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  59660. + "<b>Count</b><br>"
  59661. + "Total meshes: " + scene.meshes.length + "<br>"
  59662. + "Total lights: " + scene.lights.length + "<br>"
  59663. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  59664. + "Total materials: " + scene.materials.length + "<br>"
  59665. + "Total textures: " + scene.textures.length + "<br>"
  59666. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  59667. + "Active indices: " + scene.getActiveIndices() + "<br>"
  59668. + "Active bones: " + scene.getActiveBones() + "<br>"
  59669. + "Active particles: " + scene.getActiveParticles() + "<br>"
  59670. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  59671. + "<b>Duration</b><br>"
  59672. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  59673. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  59674. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  59675. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  59676. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  59677. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  59678. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  59679. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  59680. + "</div>"
  59681. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  59682. + "<b>Extensions</b><br>"
  59683. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  59684. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  59685. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  59686. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  59687. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  59688. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  59689. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  59690. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  59691. + "</div><br>"
  59692. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  59693. + "<b>Caps.</b><br>"
  59694. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  59695. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  59696. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  59697. + "<b>Info</b><br>"
  59698. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  59699. + glInfo.version + "<br>"
  59700. + "</div><br>"
  59701. + glInfo.renderer + "<br>";
  59702. if (this.customStatsFunction) {
  59703. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  59704. }
  59705. };
  59706. return DebugLayer;
  59707. })();
  59708. BABYLON.DebugLayer = DebugLayer;
  59709. })(BABYLON || (BABYLON = {}));
  59710. 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#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\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;\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\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;\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\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\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\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":"vec4 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}\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;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\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;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\n}\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 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\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*sizeUV.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*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.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}\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05)\ndiscard;\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt 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;\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}"};
  59711. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\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}\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;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\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;\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#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}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\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;\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#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\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\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);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\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\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}\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;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\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;\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;\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}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\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;\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;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\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);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\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"};
  59712. 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.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.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,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),r.CrossToRef(h,R,g),g.normalize(),r.Dot(a,g)<0&&(v=1),T=r.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,r.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),r.CrossToRef(_,R,b),b.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(R,g)<0&&(v=1),T=r.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,r.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,R,g),g.normalize(),r.Dot(g,m)<0&&(v=1),T=r.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},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],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+r*_+n*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*T)*F,t.m[13]=(i*v-r*g+n*T)*F,t.m[2]=(r*A-n*L+o*C)*F,t.m[6]=-(i*A-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*q+o*H)*F,t.m[7]=(i*I-n*N+o*V)*F,t.m[11]=-(i*q-r*N+o*D)*F,t.m[15]=(i*H-r*V+n*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var 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),this},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],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];\nreturn i[r]=n*v+o*R+e*F+s*P,i[r+1]=n*d+o*_+e*A+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*T+o*b+e*C+s*I,i[r+4]=h*v+a*R+u*F+m*P,i[r+5]=h*d+a*_+u*A+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*T+a*b+u*C+m*I,i[r+8]=y*v+c*R+p*F+f*P,i[r+9]=y*d+c*_+p*A+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*T+c*b+p*C+f*I,i[r+12]=l*v+x*R+z*F+w*P,i[r+13]=l*d+x*_+z*A+w*Z,i[r+14]=l*g+x*M+z*L+w*S,i[r+15]=l*T+x*b+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(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,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=r,x.m[3]=n,x.m[4]=o,x.m[5]=e,x.m[6]=s,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var 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,l,x){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]=l,z.m[15]=x,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.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/(o-e),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/(o-e),s.m[15]=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/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},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 l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,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=x;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=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var 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===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],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;if(void 0===o||null===o){var h;i.WithinEpsilon(n.y,1,t.Epsilon)?i.WithinEpsilon(n.x,1,t.Epsilon)?i.WithinEpsilon(n.z,1,t.Epsilon)||(h=new e(0,0,1)):h=new e(1,0,0):h=new e(0,-1,0),s=e.Cross(n,h)}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 T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var 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=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,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={}));";
  59713. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59714. module.exports = BABYLON;
  59715. };